<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script id="versionArea" type="text/javascript">
//<![CDATA[
var version = {title: "TiddlyWiki", major: 2, minor: 6, revision: 2, date: new Date("Jan 6, 2011"), extensions: {}};
//]]>
</script>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="copyright" content="
TiddlyWiki created by Jeremy Ruston, (jeremy [at] osmosoft [dot] com)

Copyright (c) Jeremy Ruston 2004-2007
Copyright (c) UnaMesa Association 2007-2011

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.

Neither the name of the UnaMesa Association nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
" />
<!--PRE-HEAD-START-->
<!--{{{-->
<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml' />
<!--}}}-->

<!--PRE-HEAD-END-->
<title> AnDevCon2011 Stephen Williams - JavaGlue </title>
<style id="styleArea" type="text/css">
#saveTest {display:none;}
#messageArea {display:none;}
#copyright {display:none;}
#storeArea {display:none;}
#storeArea div {padding:0.5em; margin:1em 0em 0em 0em; border-color:#fff #666 #444 #ddd; border-style:solid; border-width:2px; overflow:auto;}
#shadowArea {display:none;}
#javascriptWarning {width:100%; text-align:center; font-weight:bold; background-color:#dd1100; color:#fff; padding:1em 0em;}
</style>
<!--PRE-VAULTSTYLE-START-->
<style type="text/css">
#vaultArea {display:none;}
#vaultArea div {padding:0.5em; margin:1em 0em 0em 0em; border-color:#fff #666 #444 #ddd; border-style:solid; border-width:2px; overflow:auto;}
</style>
<!--PRE-VAULTSTYLE-END-->
<!--POST-HEAD-START-->

<!--POST-HEAD-END-->
</head>
<body onload="main();" onunload="if(window.unload) unload();">
<!--PRE-BODY-START-->

<!--PRE-BODY-END-->
<div id="copyright">
Welcome to TiddlyWiki created by Jeremy Ruston; Copyright &copy; 2004-2007 Jeremy Ruston, Copyright &copy; 2007-2011 UnaMesa Association
</div>
<noscript>
<div id="javascriptWarning">
This page requires JavaScript to function properly.<br /><br />If you are using Microsoft Internet Explorer you may need to click on the yellow bar above and select 'Allow Blocked Content'. You must then click 'Yes' on the following security warning.
</div>
</noscript>
<div id="saveTest"></div>
<div id="backstageCloak"></div>
<div id="backstageButton"></div>
<div id="backstageArea"><div id="backstageToolbar"></div></div>
<div id="backstage">
	<div id="backstagePanel"></div>
</div>
<div id="contentWrapper"></div>
<div id="contentStash"></div>
<div id="shadowArea">
<div title="MarkupPreHead">
<pre>&lt;!--{{{--&gt;
&lt;link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml' /&gt;
&lt;!--}}}--&gt;
</pre>
</div>
<div title="ColorPalette">
<pre>Background: #fff
Foreground: #000
PrimaryPale: #8cf
PrimaryLight: #18f
PrimaryMid: #04b
PrimaryDark: #014
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
</pre>
</div>
<div title="StyleSheetColors">
<pre>/*{{{*/
body {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}

a {color:[[ColorPalette::PrimaryMid]];}
a:hover {background-color:[[ColorPalette::PrimaryMid]]; color:[[ColorPalette::Background]];}
a img {border:0;}

h1,h2,h3,h4,h5,h6 {color:[[ColorPalette::SecondaryDark]]; background:transparent;}
h1 {border-bottom:2px solid [[ColorPalette::TertiaryLight]];}
h2,h3 {border-bottom:1px solid [[ColorPalette::TertiaryLight]];}

.button {color:[[ColorPalette::PrimaryDark]]; border:1px solid [[ColorPalette::Background]];}
.button:hover {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::SecondaryLight]]; border-color:[[ColorPalette::SecondaryMid]];}
.button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::SecondaryDark]];}

.header {background:[[ColorPalette::PrimaryMid]];}
.headerShadow {color:[[ColorPalette::Foreground]];}
.headerShadow a {font-weight:normal; color:[[ColorPalette::Foreground]];}
.headerForeground {color:[[ColorPalette::Background]];}
.headerForeground a {font-weight:normal; color:[[ColorPalette::PrimaryPale]];}

.tabSelected{color:[[ColorPalette::PrimaryDark]];
	background:[[ColorPalette::TertiaryPale]];
	border-left:1px solid [[ColorPalette::TertiaryLight]];
	border-top:1px solid [[ColorPalette::TertiaryLight]];
	border-right:1px solid [[ColorPalette::TertiaryLight]];
}
.tabUnselected {color:[[ColorPalette::Background]]; background:[[ColorPalette::TertiaryMid]];}
.tabContents {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::TertiaryPale]]; border:1px solid [[ColorPalette::TertiaryLight]];}
.tabContents .button {border:0;}

#sidebar {}
#sidebarOptions input {border:1px solid [[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel {background:[[ColorPalette::PrimaryPale]];}
#sidebarOptions .sliderPanel a {border:none;color:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:hover {color:[[ColorPalette::Background]]; background:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:active {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::Background]];}

.wizard {background:[[ColorPalette::PrimaryPale]]; border:1px solid [[ColorPalette::PrimaryMid]];}
.wizard h1 {color:[[ColorPalette::PrimaryDark]]; border:none;}
.wizard h2 {color:[[ColorPalette::Foreground]]; border:none;}
.wizardStep {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];
	border:1px solid [[ColorPalette::PrimaryMid]];}
.wizardStep.wizardStepDone {background:[[ColorPalette::TertiaryLight]];}
.wizardFooter {background:[[ColorPalette::PrimaryPale]];}
.wizardFooter .status {background:[[ColorPalette::PrimaryDark]]; color:[[ColorPalette::Background]];}
.wizard .button {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryLight]]; border: 1px solid;
	border-color:[[ColorPalette::SecondaryPale]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryDark]] [[ColorPalette::SecondaryPale]];}
.wizard .button:hover {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Background]];}
.wizard .button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::Foreground]]; border: 1px solid;
	border-color:[[ColorPalette::PrimaryDark]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryDark]];}

.wizard .notChanged {background:transparent;}
.wizard .changedLocally {background:#80ff80;}
.wizard .changedServer {background:#8080ff;}
.wizard .changedBoth {background:#ff8080;}
.wizard .notFound {background:#ffff80;}
.wizard .putToServer {background:#ff80ff;}
.wizard .gotFromServer {background:#80ffff;}

#messageArea {border:1px solid [[ColorPalette::SecondaryMid]]; background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]];}
#messageArea .button {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::SecondaryPale]]; border:none;}

.popupTiddler {background:[[ColorPalette::TertiaryPale]]; border:2px solid [[ColorPalette::TertiaryMid]];}

.popup {background:[[ColorPalette::TertiaryPale]]; color:[[ColorPalette::TertiaryDark]]; border-left:1px solid [[ColorPalette::TertiaryMid]]; border-top:1px solid [[ColorPalette::TertiaryMid]]; border-right:2px solid [[ColorPalette::TertiaryDark]]; border-bottom:2px solid [[ColorPalette::TertiaryDark]];}
.popup hr {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::PrimaryDark]]; border-bottom:1px;}
.popup li.disabled {color:[[ColorPalette::TertiaryMid]];}
.popup li a, .popup li a:visited {color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border: none;}
.popup li a:active {background:[[ColorPalette::SecondaryPale]]; color:[[ColorPalette::Foreground]]; border: none;}
.popupHighlight {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
.listBreak div {border-bottom:1px solid [[ColorPalette::TertiaryDark]];}

.tiddler .defaultCommand {font-weight:bold;}

.shadow .title {color:[[ColorPalette::TertiaryDark]];}

.title {color:[[ColorPalette::SecondaryDark]];}
.subtitle {color:[[ColorPalette::TertiaryDark]];}

.toolbar {color:[[ColorPalette::PrimaryMid]];}
.toolbar a {color:[[ColorPalette::TertiaryLight]];}
.selected .toolbar a {color:[[ColorPalette::TertiaryMid]];}
.selected .toolbar a:hover {color:[[ColorPalette::Foreground]];}

.tagging, .tagged {border:1px solid [[ColorPalette::TertiaryPale]]; background-color:[[ColorPalette::TertiaryPale]];}
.selected .tagging, .selected .tagged {background-color:[[ColorPalette::TertiaryLight]]; border:1px solid [[ColorPalette::TertiaryMid]];}
.tagging .listTitle, .tagged .listTitle {color:[[ColorPalette::PrimaryDark]];}
.tagging .button, .tagged .button {border:none;}

.footer {color:[[ColorPalette::TertiaryLight]];}
.selected .footer {color:[[ColorPalette::TertiaryMid]];}

.sparkline {background:[[ColorPalette::PrimaryPale]]; border:0;}
.sparktick {background:[[ColorPalette::PrimaryDark]];}

.error, .errorButton {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Error]];}
.warning {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryPale]];}
.lowlight {background:[[ColorPalette::TertiaryLight]];}

.zoomer {background:none; color:[[ColorPalette::TertiaryMid]]; border:3px solid [[ColorPalette::TertiaryMid]];}

.imageLink, #displayArea .imageLink {background:transparent;}

.annotation {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; border:2px solid [[ColorPalette::SecondaryMid]];}

.viewer .listTitle {list-style-type:none; margin-left:-2em;}
.viewer .button {border:1px solid [[ColorPalette::SecondaryMid]];}
.viewer blockquote {border-left:3px solid [[ColorPalette::TertiaryDark]];}

.viewer table, table.twtable {border:2px solid [[ColorPalette::TertiaryDark]];}
.viewer th, .viewer thead td, .twtable th, .twtable thead td {background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::Background]];}
.viewer td, .viewer tr, .twtable td, .twtable tr {border:1px solid [[ColorPalette::TertiaryDark]];}

.viewer pre {border:1px solid [[ColorPalette::SecondaryLight]]; background:[[ColorPalette::SecondaryPale]];}
.viewer code {color:[[ColorPalette::SecondaryDark]];}
.viewer hr {border:0; border-top:dashed 1px [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::TertiaryDark]];}

.highlight, .marked {background:[[ColorPalette::SecondaryLight]];}

.editor input {border:1px solid [[ColorPalette::PrimaryMid]];}
.editor textarea {border:1px solid [[ColorPalette::PrimaryMid]]; width:100%;}
.editorFooter {color:[[ColorPalette::TertiaryMid]];}
.readOnly {background:[[ColorPalette::TertiaryPale]];}

#backstageArea {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::TertiaryMid]];}
#backstageArea a {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstageArea a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; }
#backstageArea a.backstageSelTab {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
#backstageButton a {background:none; color:[[ColorPalette::Background]]; border:none;}
#backstageButton a:hover {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstagePanel {background:[[ColorPalette::Background]]; border-color: [[ColorPalette::Background]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]];}
.backstagePanelFooter .button {border:none; color:[[ColorPalette::Background]];}
.backstagePanelFooter .button:hover {color:[[ColorPalette::Foreground]];}
#backstageCloak {background:[[ColorPalette::Foreground]]; opacity:0.6; filter:'alpha(opacity=60)';}
/*}}}*/</pre>
</div>
<div title="StyleSheetLayout">
<pre>/*{{{*/
* html .tiddler {height:1%;}

body {font-size:.75em; font-family:arial,helvetica; margin:0; padding:0;}

h1,h2,h3,h4,h5,h6 {font-weight:bold; text-decoration:none;}
h1,h2,h3 {padding-bottom:1px; margin-top:1.2em;margin-bottom:0.3em;}
h4,h5,h6 {margin-top:1em;}
h1 {font-size:1.35em;}
h2 {font-size:1.25em;}
h3 {font-size:1.1em;}
h4 {font-size:1em;}
h5 {font-size:.9em;}

hr {height:1px;}

a {text-decoration:none;}

dt {font-weight:bold;}

ol {list-style-type:decimal;}
ol ol {list-style-type:lower-alpha;}
ol ol ol {list-style-type:lower-roman;}
ol ol ol ol {list-style-type:decimal;}
ol ol ol ol ol {list-style-type:lower-alpha;}
ol ol ol ol ol ol {list-style-type:lower-roman;}
ol ol ol ol ol ol ol {list-style-type:decimal;}

.txtOptionInput {width:11em;}

#contentWrapper .chkOptionInput {border:0;}

.externalLink {text-decoration:underline;}

.indent {margin-left:3em;}
.outdent {margin-left:3em; text-indent:-3em;}
code.escaped {white-space:nowrap;}

.tiddlyLinkExisting {font-weight:bold;}
.tiddlyLinkNonExisting {font-style:italic;}

/* the 'a' is required for IE, otherwise it renders the whole tiddler in bold */
a.tiddlyLinkNonExisting.shadow {font-weight:bold;}

#mainMenu .tiddlyLinkExisting,
	#mainMenu .tiddlyLinkNonExisting,
	#sidebarTabs .tiddlyLinkNonExisting {font-weight:normal; font-style:normal;}
#sidebarTabs .tiddlyLinkExisting {font-weight:bold; font-style:normal;}

.header {position:relative;}
.header a:hover {background:transparent;}
.headerShadow {position:relative; padding:4.5em 0 1em 1em; left:-1px; top:-1px;}
.headerForeground {position:absolute; padding:4.5em 0 1em 1em; left:0px; top:0px;}

.siteTitle {font-size:3em;}
.siteSubtitle {font-size:1.2em;}

#mainMenu {position:absolute; left:0; width:10em; text-align:right; line-height:1.6em; padding:1.5em 0.5em 0.5em 0.5em; font-size:1.1em;}

#sidebar {position:absolute; right:3px; width:16em; font-size:.9em;}
#sidebarOptions {padding-top:0.3em;}
#sidebarOptions a {margin:0 0.2em; padding:0.2em 0.3em; display:block;}
#sidebarOptions input {margin:0.4em 0.5em;}
#sidebarOptions .sliderPanel {margin-left:1em; padding:0.5em; font-size:.85em;}
#sidebarOptions .sliderPanel a {font-weight:bold; display:inline; padding:0;}
#sidebarOptions .sliderPanel input {margin:0 0 0.3em 0;}
#sidebarTabs .tabContents {width:15em; overflow:hidden;}

.wizard {padding:0.1em 1em 0 2em;}
.wizard h1 {font-size:2em; font-weight:bold; background:none; padding:0; margin:0.4em 0 0.2em;}
.wizard h2 {font-size:1.2em; font-weight:bold; background:none; padding:0; margin:0.4em 0 0.2em;}
.wizardStep {padding:1em 1em 1em 1em;}
.wizard .button {margin:0.5em 0 0; font-size:1.2em;}
.wizardFooter {padding:0.8em 0.4em 0.8em 0;}
.wizardFooter .status {padding:0 0.4em; margin-left:1em;}
.wizard .button {padding:0.1em 0.2em;}

#messageArea {position:fixed; top:2em; right:0; margin:0.5em; padding:0.5em; z-index:2000; _position:absolute;}
.messageToolbar {display:block; text-align:right; padding:0.2em;}
#messageArea a {text-decoration:underline;}

.tiddlerPopupButton {padding:0.2em;}
.popupTiddler {position: absolute; z-index:300; padding:1em; margin:0;}

.popup {position:absolute; z-index:300; font-size:.9em; padding:0; list-style:none; margin:0;}
.popup .popupMessage {padding:0.4em;}
.popup hr {display:block; height:1px; width:auto; padding:0; margin:0.2em 0;}
.popup li.disabled {padding:0.4em;}
.popup li a {display:block; padding:0.4em; font-weight:normal; cursor:pointer;}
.listBreak {font-size:1px; line-height:1px;}
.listBreak div {margin:2px 0;}

.tabset {padding:1em 0 0 0.5em;}
.tab {margin:0 0 0 0.25em; padding:2px;}
.tabContents {padding:0.5em;}
.tabContents ul, .tabContents ol {margin:0; padding:0;}
.txtMainTab .tabContents li {list-style:none;}
.tabContents li.listLink { margin-left:.75em;}

#contentWrapper {display:block;}
#splashScreen {display:none;}

#displayArea {margin:1em 17em 0 14em;}

.toolbar {text-align:right; font-size:.9em;}

.tiddler {padding:1em 1em 0;}

.missing .viewer,.missing .title {font-style:italic;}

.title {font-size:1.6em; font-weight:bold;}

.missing .subtitle {display:none;}
.subtitle {font-size:1.1em;}

.tiddler .button {padding:0.2em 0.4em;}

.tagging {margin:0.5em 0.5em 0.5em 0; float:left; display:none;}
.isTag .tagging {display:block;}
.tagged {margin:0.5em; float:right;}
.tagging, .tagged {font-size:0.9em; padding:0.25em;}
.tagging ul, .tagged ul {list-style:none; margin:0.25em; padding:0;}
.tagClear {clear:both;}

.footer {font-size:.9em;}
.footer li {display:inline;}

.annotation {padding:0.5em; margin:0.5em;}

* html .viewer pre {width:99%; padding:0 0 1em 0;}
.viewer {line-height:1.4em; padding-top:0.5em;}
.viewer .button {margin:0 0.25em; padding:0 0.25em;}
.viewer blockquote {line-height:1.5em; padding-left:0.8em;margin-left:2.5em;}
.viewer ul, .viewer ol {margin-left:0.5em; padding-left:1.5em;}

.viewer table, table.twtable {border-collapse:collapse; margin:0.8em 1.0em;}
.viewer th, .viewer td, .viewer tr,.viewer caption,.twtable th, .twtable td, .twtable tr,.twtable caption {padding:3px;}
table.listView {font-size:0.85em; margin:0.8em 1.0em;}
table.listView th, table.listView td, table.listView tr {padding:0px 3px 0px 3px;}

.viewer pre {padding:0.5em; margin-left:0.5em; font-size:1.2em; line-height:1.4em; overflow:auto;}
.viewer code {font-size:1.2em; line-height:1.4em;}

.editor {font-size:1.1em;}
.editor input, .editor textarea {display:block; width:100%; font:inherit;}
.editorFooter {padding:0.25em 0; font-size:.9em;}
.editorFooter .button {padding-top:0px; padding-bottom:0px;}

.fieldsetFix {border:0; padding:0; margin:1px 0px;}

.sparkline {line-height:1em;}
.sparktick {outline:0;}

.zoomer {font-size:1.1em; position:absolute; overflow:hidden;}
.zoomer div {padding:1em;}

* html #backstage {width:99%;}
* html #backstageArea {width:99%;}
#backstageArea {display:none; position:relative; overflow: hidden; z-index:150; padding:0.3em 0.5em;}
#backstageToolbar {position:relative;}
#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em;}
#backstageButton {display:none; position:absolute; z-index:175; top:0; right:0;}
#backstageButton a {padding:0.1em 0.4em; margin:0.1em;}
#backstage {position:relative; width:100%; z-index:50;}
#backstagePanel {display:none; z-index:100; position:absolute; width:90%; margin-left:3em; padding:1em;}
.backstagePanelFooter {padding-top:0.2em; float:right;}
.backstagePanelFooter a {padding:0.2em 0.4em;}
#backstageCloak {display:none; z-index:20; position:absolute; width:100%; height:100px;}

.whenBackstage {display:none;}
.backstageVisible .whenBackstage {display:block;}
/*}}}*/
</pre>
</div>
<div title="StyleSheetLocale">
<pre>/***
StyleSheet for use when a translation requires any css style changes.
This StyleSheet can be used directly by languages such as Chinese, Japanese and Korean which need larger font sizes.
***/
/*{{{*/
body {font-size:0.8em;}
#sidebarOptions {font-size:1.05em;}
#sidebarOptions a {font-style:normal;}
#sidebarOptions .sliderPanel {font-size:0.95em;}
.subtitle {font-size:0.8em;}
.viewer table.listView {font-size:0.95em;}
/*}}}*/</pre>
</div>
<div title="StyleSheetPrint">
<pre>/*{{{*/
@media print {
#mainMenu, #sidebar, #messageArea, .toolbar, #backstageButton, #backstageArea {display: none !important;}
#displayArea {margin: 1em 1em 0em;}
noscript {display:none;} /* Fixes a feature in Firefox 1.5.0.2 where print preview displays the noscript content */
}
/*}}}*/</pre>
</div>
<div title="PageTemplate">
<pre>&lt;!--{{{--&gt;
&lt;div class='header' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'&gt;
&lt;div class='headerShadow'&gt;
&lt;span class='siteTitle' refresh='content' tiddler='SiteTitle'&gt;&lt;/span&gt;&amp;nbsp;
&lt;span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div class='headerForeground'&gt;
&lt;span class='siteTitle' refresh='content' tiddler='SiteTitle'&gt;&lt;/span&gt;&amp;nbsp;
&lt;span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id='mainMenu' refresh='content' tiddler='MainMenu'&gt;&lt;/div&gt;
&lt;div id='sidebar'&gt;
&lt;div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'&gt;&lt;/div&gt;
&lt;div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div id='displayArea'&gt;
&lt;div id='messageArea'&gt;&lt;/div&gt;
&lt;div id='tiddlerDisplay'&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;!--}}}--&gt;</pre>
</div>
<div title="ViewTemplate">
<pre>&lt;!--{{{--&gt;
&lt;div class='toolbar' macro='toolbar [[ToolbarCommands::ViewToolbar]]'&gt;&lt;/div&gt;
&lt;div class='title' macro='view title'&gt;&lt;/div&gt;
&lt;div class='subtitle'&gt;&lt;span macro='view modifier link'&gt;&lt;/span&gt;, &lt;span macro='view modified date'&gt;&lt;/span&gt; (&lt;span macro='message views.wikified.createdPrompt'&gt;&lt;/span&gt; &lt;span macro='view created date'&gt;&lt;/span&gt;)&lt;/div&gt;
&lt;div class='tagging' macro='tagging'&gt;&lt;/div&gt;
&lt;div class='tagged' macro='tags'&gt;&lt;/div&gt;
&lt;div class='viewer' macro='view text wikified'&gt;&lt;/div&gt;
&lt;div class='tagClear'&gt;&lt;/div&gt;
&lt;!--}}}--&gt;</pre>
</div>
<div title="EditTemplate">
<pre>&lt;!--{{{--&gt;
&lt;div class='toolbar' macro='toolbar [[ToolbarCommands::EditToolbar]]'&gt;&lt;/div&gt;
&lt;div class='title' macro='view title'&gt;&lt;/div&gt;
&lt;div class='editor' macro='edit title'&gt;&lt;/div&gt;
&lt;div macro='annotations'&gt;&lt;/div&gt;
&lt;div class='editor' macro='edit text'&gt;&lt;/div&gt;
&lt;div class='editor' macro='edit tags'&gt;&lt;/div&gt;&lt;div class='editorFooter'&gt;&lt;span macro='message views.editor.tagPrompt'&gt;&lt;/span&gt;&lt;span macro='tagChooser excludeLists'&gt;&lt;/span&gt;&lt;/div&gt;
&lt;!--}}}--&gt;</pre>
</div>
<div title="GettingStarted">
<pre>To get started with this blank [[TiddlyWiki]], you'll need to modify the following tiddlers:
* [[SiteTitle]] &amp; [[SiteSubtitle]]: The title and subtitle of the site, as shown above (after saving, they will also appear in the browser title bar)
* [[MainMenu]]: The menu (usually on the left)
* [[DefaultTiddlers]]: Contains the names of the tiddlers that you want to appear when the TiddlyWiki is opened
You'll also need to enter your username for signing your edits: &lt;&lt;option txtUserName&gt;&gt;</pre>
</div>
<div title="OptionsPanel">
<pre>These [[InterfaceOptions]] for customising [[TiddlyWiki]] are saved in your browser

Your username for signing your edits. Write it as a [[WikiWord]] (eg [[JoeBloggs]])

&lt;&lt;option txtUserName&gt;&gt;
&lt;&lt;option chkSaveBackups&gt;&gt; [[SaveBackups]]
&lt;&lt;option chkAutoSave&gt;&gt; [[AutoSave]]
&lt;&lt;option chkRegExpSearch&gt;&gt; [[RegExpSearch]]
&lt;&lt;option chkCaseSensitiveSearch&gt;&gt; [[CaseSensitiveSearch]]
&lt;&lt;option chkAnimate&gt;&gt; [[EnableAnimations]]

----
Also see [[AdvancedOptions]]</pre>
</div>
<div title="ImportTiddlers">
<pre>&lt;&lt;importTiddlers&gt;&gt;</pre>
</div>
</div>
<!--POST-SHADOWAREA-->
<div id="vaultArea"></div>
<!--POST-VAULTAREA-->
<div id="storeArea">
<div title="AnDevCon2011" modifier="StephenWilliams" created="201103080011" modified="201104040137" tags="AnDevCon2011 Ssx JavaGlue" changecount="25">
<pre>!Select a presentation:  [[Ssx|#tag:Ssx]] ([[Video|http://sdw.st/video/Ssx/index.html]]) - [[JavaGlue|#tag:JavaGlue]] ([[Video|http://sdw.st/video/JavaGlue/index.html]])
/% &lt;&lt;tiddler OpenTaggedTiddlers with: Ssx Ssx close &gt;&gt;  &lt;&lt;tiddler OpenTaggedTiddlers with: JavaGlue JavaGlue close &gt;&gt; %/This document lives at: http://sdw.st/javaglue.html http://sdw.st/conf/AnDevCon2011/sdwAnDevCon2011.html  and is also referenced from: https://sites.google.com/site/xbigdocs/
Please email with comments, interest, or if you are planning to use these tools: [[sdw@lig.net|mailto:sdw@lig.net]].  I'd like to know who's interested, and who to email with notifications of updates.

This is a [[TiddlyWiki|http://mptw.tiddlyspot.com/]], to be exact: the [[MPTW Tiddlywiki|http://mptw.tiddlyspot.com/]] (version &lt;&lt;mptwVersion&gt;&gt;) + SyntaxHighlighterPlugin and others.  See TiddlerReference if you don't know what a [[TiddlyWiki|http://mptw.tiddlyspot.com/]] is.
</pre>
</div>
<div title="C" modifier="Jonny Gerold" created="201012140353" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201012140353">
<pre>* [[Books]]
**	[[The C Programming Language]]</pre>
</div>
<div title="C++" modifier="Jonny Gerold" created="201008102233" modified="201012140353" tags="Programming" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201012140353">
<pre>* [[Books]]
**	[[The C++ Programming Language]]</pre>
</div>
<div title="CascadingExcludeListsHack" modifier="Pascal" created="200801071432" tags="systemConfig" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200801071432">
<pre>//{{{
TiddlyWiki.prototype.getCascadingTaggedTiddlers = function(lookupValue,lookupMatch,sortField)
{
	var candidates =[];
	store.forEachTiddler(function(title,tiddler) {if (tiddler.isTagged(lookupValue)) candidates.push(title)})
	var results = [];
	this.forEachTiddler(function(title,tiddler) {
		var f = !lookupMatch;
		for(var lookup=0; lookup&lt;tiddler.tags.length; lookup++) {
			if((tiddler.tags[lookup]== lookupValue)|| (candidates.indexOf(tiddler.tags[lookup])&gt;=0))
				f = lookupMatch;
		}
		if(f)
			results.push(tiddler);
	});
	if(!sortField)
		sortField = &quot;title&quot;;
	results.sort(function(a,b) {return a[sortField] &lt; b[sortField] ? -1 : (a[sortField] == b[sortField] ? 0 : +1);});
	return results;
};

config.macros.timeline.handler = function(place,macroName,params)
{
	var field = params[0] ? params[0] : &quot;modified&quot;;
	var tiddlers = store.getCascadingTaggedTiddlers(&quot;excludeLists&quot;,false,field);
	var lastDay = &quot;&quot;;
	var last = params[1] ? tiddlers.length-Math.min(tiddlers.length,parseInt(params[1])) : 0;
	var dateFormat = params[2] ? params[2] : this.dateFormat;
	for(var t=tiddlers.length-1; t&gt;=last; t--) {
		var tiddler = tiddlers[t];
		var theDay = tiddler[field].convertToLocalYYYYMMDDHHMM().substr(0,8);
		if(theDay != lastDay) {
			var ul = document.createElement(&quot;ul&quot;);
			place.appendChild(ul);
			createTiddlyElement(ul,&quot;li&quot;,null,&quot;listTitle&quot;,tiddler[field].formatString(dateFormat));
			lastDay = theDay;
		}
		createTiddlyElement(ul,&quot;li&quot;,null,&quot;listLink&quot;).appendChild(createTiddlyLink(place,tiddler.title,true));
	}
};

config.macros.list.all.handler = function(params)
{
	return store.getCascadingTaggedTiddlers(&quot;excludeLists&quot;,false,&quot;title&quot;);
};
//}}}</pre>
</div>
<div title="CloseOnCancelPlugin" modifier="MPTW" created="201004131209" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|CloseOnCancelPlugin|
|Description:|Closes the tiddler if you click new tiddler then cancel. Default behaviour is to leave it open|
|Version:|3.0.1 ($Rev: 3861 $)|
|Date:|$Date: 2008-03-08 10:53:09 +1000 (Sat, 08 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#CloseOnCancelPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
***/
//{{{
merge(config.commands.cancelTiddler,{

	handler_mptw_orig_closeUnsaved: config.commands.cancelTiddler.handler,

	handler: function(event,src,title) {
		this.handler_mptw_orig_closeUnsaved(event,src,title);
		if (!story.isDirty(title) &amp;&amp; !store.tiddlerExists(title) &amp;&amp; !store.isShadowTiddler(title))
			story.closeTiddler(title,true);
		return false;
	}

});

//}}}

</pre>
</div>
<div title="Concise Coding" modifier="StephenWilliams" created="201103081911" modified="201103090725" tags="AnDevCon2011 ConciseCoding" changecount="12">
<pre>Most code is far from optimal.  It is too verbose, sometimes having hundreds of classes, and use many lines of code to do things that should be done in a single line.  Interfaces are complicated, combining libraries and techniques often create a combinatorial explosion of total complexity.  The chronic application of &quot;keep it simple&quot;, &quot;don't put too much code in one place&quot;, &quot;we don't have time to rewrite that code&quot; results in code that is far, far more complex than it should be.

In addition to problems in project management and architecture / high-level design, detailed design and coding frequently suffers from over-application of methods and design rules which leads to inefficiency, pain, suffering, and project failure. Management challenges are answered somewhat by Agile, Scrum, etc.
There are many architectural methods and principles that are very helpful.  These are also managed with iterative &amp; Agile methods and best emerging practice.  However, in very successful projects, applying just the right techniques in a sparing way to get lowest total complexity requires competent, experienced architect coders with the right goals.  These are guidelines for choosing those goals.
# Apply architectural principles and design methodologies, recommended design rules, and favor use of well-known APIs and architectures
# Always counterbalance with consideration overall complexity for application developers, maintenance, and reuse
# Favor creating tools and libraries to concentrate complexity to keep application development as simple and concise as possible
# Develop and use design rules for when *not* to create new classes, files, packages, etc.
## Avoid &quot;class diarrhea&quot;: Most developers seem to have many reasons to create new classes and practically no reasons not to.
### Tools are making this worse.  Peephole, tool-tip driven development can lead to a system that is impossible to grok as a whole.  Development can grind to a halt as it becomes more and more difficult to make changes.
## Don't pollute the namespace, class &quot;space&quot;, file &quot;space&quot;, etc.
## Strive to reduce total &quot;surface area&quot; (the total cognitive load) at each level.
## Architect for flexibility, but recognize when the flexibility is not needed.  (Do you really need to create an indirection for a constant like &quot;http://&quot;?  Is it going to change?  Does it need translation?  What are you doing???)
# Be object-oriented at the macro level too
## Keep everything together when possible and lowest complexity.
## Expect code reuse: Can a class be copied easily to another project / package, or do all classes form a complex web.  Having to change more than a class or two for incremental additions is a good sign that something is wrong.
## Don't ever hide application flow, configuration, and dependencies.
## Avoid creating interfaces and classes just to pass, return, and store tuples.
### In some cases, Map&lt;&gt; or String[]/Object[] can be appropriate.  (Similar to C++ pair&lt;&gt; or Qt/C++ or Objective-C properties or even Lisp lists.)
### Use generic callback interfaces for generic solutions.
### If a custom composite return type or callback interface is desired, declare it in an inner class right next to where it is used, unless it is a very standard and common element in a system.
# Don't avoid refactoring or even a total rewrite
## Recognize that developers are experts at the problem *after* they have created an initial design and implemented it.  Frequently, what seemed appropriate before solving all of the details is, later, clearly not the best.  Expect this.  Redesign and rewrite at stopping points or when development is slowing.
## Working code can usually be rewritten much faster than the original: You are not wasting all prior effort.
## Rewrite in parallel to existing code when possible which can allow toggling or running both paths and comparing the results.
# Use or Create new conventions and methods that improve complexity
## Little things like coding conventions
### Favor reducing vertical white space: Seeing more code at once is useful. (I prefer K&amp;R for that reason.)
### Use special rules when necessary: &quot;paragraph mode&quot; for intense, dense coding: See Ssx.SParse.
## Big things like architectural patterns
### Signals / Slots, message based, queues, logging/debugging, ...
!Concise Coding: The Book
Planning to write a book on this later in the year.  Email with peeves, examples, comments, reviewing interest: sdw@lig.net

[[Back to Ssx|Ssx]]</pre>
</div>
<div title="CryptoFunctionsPlugin" created="200710131134" tags="systemConfig excludeLists excludeSearch" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200710131134">
<pre>/***
|''Name:''|CryptoFunctionsPlugin|
|''Description:''|Support for cryptographic functions|
***/
//{{{
if(!version.extensions.CryptoFunctionsPlugin) {
version.extensions.CryptoFunctionsPlugin = {installed:true};

//--
//-- Crypto functions and associated conversion routines
//--

// Crypto &quot;namespace&quot;
function Crypto() {}

// Convert a string to an array of big-endian 32-bit words
Crypto.strToBe32s = function(str)
{
	var be = Array();
	var len = Math.floor(str.length/4);
	var i, j;
	for(i=0, j=0; i&lt;len; i++, j+=4) {
		be[i] = ((str.charCodeAt(j)&amp;0xff) &lt;&lt; 24)|((str.charCodeAt(j+1)&amp;0xff) &lt;&lt; 16)|((str.charCodeAt(j+2)&amp;0xff) &lt;&lt; 8)|(str.charCodeAt(j+3)&amp;0xff);
	}
	while (j&lt;str.length) {
		be[j&gt;&gt;2] |= (str.charCodeAt(j)&amp;0xff)&lt;&lt;(24-(j*8)%32);
		j++;
	}
	return be;
};

// Convert an array of big-endian 32-bit words to a string
Crypto.be32sToStr = function(be)
{
	var str = &quot;&quot;;
	for(var i=0;i&lt;be.length*32;i+=8)
		str += String.fromCharCode((be[i&gt;&gt;5]&gt;&gt;&gt;(24-i%32)) &amp; 0xff);
	return str;
};

// Convert an array of big-endian 32-bit words to a hex string
Crypto.be32sToHex = function(be)
{
	var hex = &quot;0123456789ABCDEF&quot;;
	var str = &quot;&quot;;
	for(var i=0;i&lt;be.length*4;i++)
		str += hex.charAt((be[i&gt;&gt;2]&gt;&gt;((3-i%4)*8+4))&amp;0xF) + hex.charAt((be[i&gt;&gt;2]&gt;&gt;((3-i%4)*8))&amp;0xF);
	return str;
};

// Return, in hex, the SHA-1 hash of a string
Crypto.hexSha1Str = function(str)
{
	return Crypto.be32sToHex(Crypto.sha1Str(str));
};

// Return the SHA-1 hash of a string
Crypto.sha1Str = function(str)
{
	return Crypto.sha1(Crypto.strToBe32s(str),str.length);
};

// Calculate the SHA-1 hash of an array of blen bytes of big-endian 32-bit words
Crypto.sha1 = function(x,blen)
{
	// Add 32-bit integers, wrapping at 32 bits
	add32 = function(a,b)
	{
		var lsw = (a&amp;0xFFFF)+(b&amp;0xFFFF);
		var msw = (a&gt;&gt;16)+(b&gt;&gt;16)+(lsw&gt;&gt;16);
		return (msw&lt;&lt;16)|(lsw&amp;0xFFFF);
	};
	// Add five 32-bit integers, wrapping at 32 bits
	add32x5 = function(a,b,c,d,e)
	{
		var lsw = (a&amp;0xFFFF)+(b&amp;0xFFFF)+(c&amp;0xFFFF)+(d&amp;0xFFFF)+(e&amp;0xFFFF);
		var msw = (a&gt;&gt;16)+(b&gt;&gt;16)+(c&gt;&gt;16)+(d&gt;&gt;16)+(e&gt;&gt;16)+(lsw&gt;&gt;16);
		return (msw&lt;&lt;16)|(lsw&amp;0xFFFF);
	};
	// Bitwise rotate left a 32-bit integer by 1 bit
	rol32 = function(n)
	{
		return (n&gt;&gt;&gt;31)|(n&lt;&lt;1);
	};

	var len = blen*8;
	// Append padding so length in bits is 448 mod 512
	x[len&gt;&gt;5] |= 0x80 &lt;&lt; (24-len%32);
	// Append length
	x[((len+64&gt;&gt;9)&lt;&lt;4)+15] = len;
	var w = Array(80);

	var k1 = 0x5A827999;
	var k2 = 0x6ED9EBA1;
	var k3 = 0x8F1BBCDC;
	var k4 = 0xCA62C1D6;

	var h0 = 0x67452301;
	var h1 = 0xEFCDAB89;
	var h2 = 0x98BADCFE;
	var h3 = 0x10325476;
	var h4 = 0xC3D2E1F0;

	for(var i=0;i&lt;x.length;i+=16) {
		var j,t;
		var a = h0;
		var b = h1;
		var c = h2;
		var d = h3;
		var e = h4;
		for(j = 0;j&lt;16;j++) {
			w[j] = x[i+j];
			t = add32x5(e,(a&gt;&gt;&gt;27)|(a&lt;&lt;5),d^(b&amp;(c^d)),w[j],k1);
			e=d; d=c; c=(b&gt;&gt;&gt;2)|(b&lt;&lt;30); b=a; a = t;
		}
		for(j=16;j&lt;20;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a&gt;&gt;&gt;27)|(a&lt;&lt;5),d^(b&amp;(c^d)),w[j],k1);
			e=d; d=c; c=(b&gt;&gt;&gt;2)|(b&lt;&lt;30); b=a; a = t;
		}
		for(j=20;j&lt;40;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a&gt;&gt;&gt;27)|(a&lt;&lt;5),b^c^d,w[j],k2);
			e=d; d=c; c=(b&gt;&gt;&gt;2)|(b&lt;&lt;30); b=a; a = t;
		}
		for(j=40;j&lt;60;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a&gt;&gt;&gt;27)|(a&lt;&lt;5),(b&amp;c)|(d&amp;(b|c)),w[j],k3);
			e=d; d=c; c=(b&gt;&gt;&gt;2)|(b&lt;&lt;30); b=a; a = t;
		}
		for(j=60;j&lt;80;j++) {
			w[j] = rol32(w[j-3]^w[j-8]^w[j-14]^w[j-16]);
			t = add32x5(e,(a&gt;&gt;&gt;27)|(a&lt;&lt;5),b^c^d,w[j],k4);
			e=d; d=c; c=(b&gt;&gt;&gt;2)|(b&lt;&lt;30); b=a; a = t;
		}

		h0 = add32(h0,a);
		h1 = add32(h1,b);
		h2 = add32(h2,c);
		h3 = add32(h3,d);
		h4 = add32(h4,e);
	}
	return Array(h0,h1,h2,h3,h4);
};


}
//}}}</pre>
</div>
<div title="DefaultTiddlers" modifier="StephenWilliams" created="201103080015" modified="201103192212" changecount="3">
<pre>[[AnDevCon2011]]
[[JavaGlue.00 Agenda]]
[[JavaGlue.01 About]]
[[JavaGlue.02 Improvements]]
[[JavaGlue.03 JNI Primer]]
[[JavaGlue.04 Alternatives]]
[[JavaGlue.04.1 JNI Diagrams]]
[[JavaGlue.05 Use]]
[[JavaGlue.05.1 Example 1]]
[[JavaGlue.05.2 JavaGlue Diagrams]]
[[JavaGlue.06 JavaGlue Build System]]
[[JavaGlue.07 Memory Management]]
[[JavaGlue.08 Utility Methods]]
[[JavaGlue.10 Internals]]
[[JavaGlue.11 Advanced JNI]]
[[JavaGlue.12 CMake]]
[[Concise Coding]]
[[Ssx]]
[[Ssx API]]
[[Ssx Part 2]]
</pre>
</div>
<div title="EasyEditDocStyleSheet" modifier="Pascal" created="200711081456" modified="200712121250" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712121250">
<pre>/*{{{*/
body {color:#444; font-size:0.75em;line-height:1.4em;font-family:arial,helvetica;margin : 0.5em; padding : 0;}
html {border:0}
a, a:link, a:visited, a:active {text-decoration:none;color:#BB4400;font-weight:bold}
ul, ol {margin-left:0.5em;padding-left:1.5em;}
/*}}}*/</pre>
</div>
<div title="EasyEditPlugin" modifier="YourName" created="200710151212" modified="200801072245" tags="VisualTW Wysiwyg systemConfig" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200801072245" index="1">
<pre>/***
|''Name:''|EasyEditPlugin|
|''Description:''|Lite and extensible Wysiwyg editor for TiddlyWiki.|
|''Version:''|1.3.3|
|''Date:''|Dec 21,2007|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0|
!Demo
*On the plugin [[homepage|http://visualtw.ouvaton.org/VisualTW.html]], see [[WysiwygDemo]] and use the {{{write}}} button.
!Installation
#import the plugin,
#save and reload,
#use the &lt;&lt;toolbar easyEdit&gt;&gt; button in the tiddler's toolbar (in default ViewTemplate) or add {{{easyEdit}}} command in your own toolbar.
! Useful Addons
*[[HTMLFormattingPlugin|http://www.tiddlytools.com/#HTMLFormattingPlugin]] to embed wiki syntax in html tiddlers.&lt;&lt;br&gt;&gt;//__Tips__ : When this plugin is installed, you can use anchor syntax to link tiddlers in wysiwyg mode (example : #example). Anchors are converted back and from wiki syntax when editing.//
*[[TaggedTemplateTweak|http://www.TiddlyTools.com/#TaggedTemplateTweak]] to use alternative ViewTemplate/EditTemplate for tiddler's tagged with specific tag values.
!Configuration
|Buttons in the toolbar (empty = all).&lt;&lt;br&gt;&gt;//Example : bold,underline,separator,forecolor//&lt;&lt;br&gt;&gt;The buttons will appear in this order.| &lt;&lt;option txtEasyEditorButtons&gt;&gt;|
|EasyEditor default height | &lt;&lt;option txtEasyEditorHeight&gt;&gt;|
|Stylesheet applied to the edited richtext |[[EasyEditDocStyleSheet]]|
|Template called by the {{{write}}} button |[[EasyEditTemplate]]|
!How to extend EasyEditor
*To add your own buttons, add some code like the following in a systemConfig tagged tiddler (//use the prompt attribute only if there is a parameter//) :
**{{{EditorToolbar.buttons.heading = {label:&quot;H&quot;, toolTip : &quot;Set heading level&quot;, prompt: &quot;Enter heading level&quot;};}}} 
**{{{EditorToolbar.buttonsList +=&quot;,heading&quot;;}}}
*To get the list of all possible commands, see the documentation of the [[Gecko built-in rich text editor|http://developer.mozilla.org/en/docs/Midas]] or the [[IE command identifiers|http://msdn2.microsoft.com/en-us/library/ms533049.aspx]].
*To go further in customization, see [[Link button|EasyEditPlugin-LinkButton]] as an example.
!Code
***/

//{{{

var geckoEditor={};
var IEeditor={};

config.options.txtEasyEditorHeight = config.options.txtEasyEditorHeight ? config.options.txtEasyEditorHeight : &quot;500px&quot;;
config.options.txtEasyEditorButtons = config.options.txtEasyEditorButtons ? config.options.txtEasyEditorButtons : &quot;&quot;;

// TW2.1.x compatibility
config.browser.isGecko = config.browser.isGecko ? config.browser.isGecko : (config.userAgent.indexOf(&quot;gecko&quot;) != -1); 
config.macros.annotations = config.macros.annotations ? config.macros.annotations : {handler : function() {}}


// EASYEDITOR MACRO

config.macros.easyEdit = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		var field = params[0];
		var height = params[1] ? params[1] : config.options.txtEasyEditorHeight;
		var editor = field ? new easyEditor(tiddler,field,place,height) : null;
	},
	gather: function(element){
		var iframes = element.getElementsByTagName(&quot;iframe&quot;);
		if (iframes.length!=1) return null
		var text = &quot;&lt;html&gt;&quot;+iframes[0].contentWindow.document.body.innerHTML+&quot;&lt;/html&gt;&quot;;
		text = config.browser.isGecko ? geckoEditor.postProcessor(text) : (config.browser.isIE ? IEeditor.postProcessor(text) : text);
		return text;
	}
}

// EASYEDITOR CLASS

function easyEditor(tiddler,field,place,height) {
	this.tiddler = tiddler;
	this.field = field;
	this.browser = config.browser.isGecko ? geckoEditor : (config.browser.isIE ? IEeditor : null);
	this.wrapper = createTiddlyElement(place,&quot;div&quot;,null,&quot;easyEditor&quot;);
	this.wrapper.setAttribute(&quot;easyEdit&quot;,this.field);
	this.iframe = createTiddlyElement(null,&quot;iframe&quot;);
	this.browser.setupFrame(this.iframe,height,contextualCallback(this,this.onload));
	this.wrapper.appendChild(this.iframe);
}

easyEditor.prototype.onload = function(){
	this.editor = this.iframe.contentWindow;
	this.doc = this.editor.document;
	if (!this.browser.isDocReady(this.doc)) return null;
	
	if (!this.tiddler.isReadOnly() &amp;&amp; this.doc.designMode.toLowerCase()!=&quot;on&quot;) {
		this.doc.designMode = &quot;on&quot;;
		if (this.browser.reloadOnDesignMode) return false;	// IE fire readystatechange after designMode change
	}
	
	var internalCSS = store.getTiddlerText(&quot;EasyEditDocStyleSheet&quot;);
	setStylesheet(internalCSS,&quot;EasyEditDocStyleSheet&quot;,this.doc);
	this.browser.initContent(this.doc,store.getValue(this.tiddler,this.field));

	var barElement=createTiddlyElement(null,&quot;div&quot;,null,&quot;easyEditorToolBar&quot;);
	this.wrapper.insertBefore(barElement,this.wrapper.firstChild);
	this.toolbar = new EditorToolbar(this.doc,barElement,this.editor);

	this.browser.plugEvents(this.doc,contextualCallback(this,this.scheduleButtonsRefresh));
	this.editor.focus();
}

easyEditor.SimplePreProcessoror = function(text) {
	var re = /^&lt;html&gt;(.*)&lt;\/html&gt;$/m;
	var htmlValue = re.exec(text);
	var value = (htmlValue &amp;&amp; (htmlValue.length&gt;0)) ? htmlValue[1] : text;
	return value;
}

easyEditor.prototype.scheduleButtonsRefresh=function() { //doesn't refresh buttons state when rough typing
	if (this.nextUpdate) window.clearTimeout(this.nextUpdate);
	this.nextUpdate = window.setTimeout(contextualCallback(this.toolbar,EditorToolbar.onUpdateButton),easyEditor.buttonDelay);
}

easyEditor.buttonDelay = 200;

// TOOLBAR CLASS

function EditorToolbar(target,parent,window){
	this.target = target;
	this.window=window;
	this.elements={};
	var row = createTiddlyElement(createTiddlyElement(createTiddlyElement(parent,&quot;table&quot;),&quot;tbody&quot;),&quot;tr&quot;);
	var buttons = (config.options.txtEasyEditorButtons ? config.options.txtEasyEditorButtons : EditorToolbar.buttonsList).split(&quot;,&quot;);
	for(var cpt = 0; cpt &lt; buttons.length; cpt++){
		var b = buttons[cpt];
		var button = EditorToolbar.buttons[b];
		if (button) {
			if (button.separator)
				createTiddlyElement(row,&quot;td&quot;,null,&quot;separator&quot;).innerHTML+=&quot;&amp;nbsp;&quot;;
			else {
				var cell=createTiddlyElement(row,&quot;td&quot;,null,b+&quot;Button&quot;);
				if (button.onCreate) button.onCreate.call(this, cell, b);
				else EditorToolbar.createButton.call(this, cell, b);
			}
		}
	}
}

EditorToolbar.createButton = function(place,name){
	this.elements[name] = createTiddlyButton(place,EditorToolbar.buttons[name].label,EditorToolbar.buttons[name].toolTip,contextualCallback(this,EditorToolbar.onCommand(name)),&quot;button&quot;);
}

EditorToolbar.onCommand = function(name){
	var button = EditorToolbar.buttons[name];
	return function(){
		var parameter = false;
		if (button.prompt) {
			var parameter = this.target.queryCommandValue(name);
			parameter = prompt(button.prompt,parameter);
		}
		if (parameter != null) {
			this.target.execCommand(name, false, parameter);
			EditorToolbar.onUpdateButton.call(this);
		}
		return false;
	}
}

EditorToolbar.getCommandState = function(target,name){
	try {return target.queryCommandState(name)}
	catch(e){return false}
}

EditorToolbar.onRefreshButton = function (name){
	if (EditorToolbar.getCommandState(this.target,name)) addClass(this.elements[name].parentNode,&quot;buttonON&quot;);
	else removeClass(this.elements[name].parentNode,&quot;buttonON&quot;);
	this.window.focus();
}

EditorToolbar.onUpdateButton = function(){
	for (b in this.elements) 
		if (EditorToolbar.buttons[b].onRefresh) EditorToolbar.buttons[b].onRefresh.call(this,b);
		else EditorToolbar.onRefreshButton.call(this,b);
}

EditorToolbar.buttons = {
	separator : {separator : true},
	bold : {label:&quot;B&quot;, toolTip : &quot;Bold&quot;},
	italic : {label:&quot;I&quot;, toolTip : &quot;Italic&quot;},
	underline : {label:&quot;U&quot;, toolTip : &quot;Underline&quot;},
	strikethrough : {label:&quot;S&quot;, toolTip : &quot;Strikethrough&quot;},
	insertunorderedlist : {label:&quot;\u25CF&quot;, toolTip : &quot;Unordered list&quot;},
	insertorderedlist : {label:&quot;1.&quot;, toolTip : &quot;Ordered list&quot;},
	justifyleft : {label:&quot;[\u2261&quot;, toolTip : &quot;Align left&quot;},
	justifyright : {label:&quot;\u2261]&quot;, toolTip : &quot;Align right&quot;},
	justifycenter : {label:&quot;\u2261&quot;, toolTip : &quot;Align center&quot;},
	justifyfull : {label:&quot;[\u2261]&quot;, toolTip : &quot;Justify&quot;},
	removeformat : {label:&quot;\u00F8&quot;, toolTip : &quot;Remove format&quot;},
	fontsize : {label:&quot;\u00B1&quot;, toolTip : &quot;Set font size&quot;, prompt: &quot;Enter font size&quot;},
	forecolor : {label:&quot;C&quot;, toolTip : &quot;Set font color&quot;, prompt: &quot;Enter font color&quot;},
	fontname : {label:&quot;F&quot;, toolTip : &quot;Set font name&quot;, prompt: &quot;Enter font name&quot;},
	heading : {label:&quot;H&quot;, toolTip : &quot;Set heading level&quot;, prompt: &quot;Enter heading level (example : h1, h2, ...)&quot;},
	indent : {label:&quot;\u2192[&quot;, toolTip : &quot;Indent paragraph&quot;},
	outdent : {label:&quot;[\u2190&quot;, toolTip : &quot;Outdent paragraph&quot;},
	inserthorizontalrule : {label:&quot;\u2014&quot;, toolTip : &quot;Insert an horizontal rule&quot;},
	insertimage : {label:&quot;\u263C&quot;, toolTip : &quot;Insert image&quot;, prompt: &quot;Enter image url&quot;}
}

EditorToolbar.buttonsList = &quot;bold,italic,underline,strikethrough,separator,increasefontsize,decreasefontsize,fontsize,forecolor,fontname,separator,removeformat,separator,insertparagraph,insertunorderedlist,insertorderedlist,separator,justifyleft,justifyright,justifycenter,justifyfull,indent,outdent,separator,heading,separator,inserthorizontalrule,insertimage&quot;;

if (config.browser.isGecko) {
	EditorToolbar.buttons.increasefontsize = {onCreate : EditorToolbar.createButton, label:&quot;A&quot;, toolTip : &quot;Increase font size&quot;};
	EditorToolbar.buttons.decreasefontsize = {onCreate : EditorToolbar.createButton, label:&quot;A&quot;, toolTip : &quot;Decrease font size&quot;};
	EditorToolbar.buttons.insertparagraph = {label:&quot;P&quot;, toolTip : &quot;Format as paragraph&quot;};
}

// GECKO (FIREFOX, ...) BROWSER SPECIFIC METHODS

geckoEditor.setupFrame = function(iframe,height,callback) {
	iframe.setAttribute(&quot;style&quot;,&quot;width: 100%; height:&quot; + height);
	iframe.addEventListener(&quot;load&quot;,callback,true);
}

geckoEditor.plugEvents = function(doc,onchange){
	doc.addEventListener(&quot;keyup&quot;, onchange, true);
	doc.addEventListener(&quot;keydown&quot;, onchange, true);
	doc.addEventListener(&quot;click&quot;, onchange, true);
}

geckoEditor.postProcessor = function(text){return text};

geckoEditor.preProcessor = function(text){return easyEditor.SimplePreProcessoror(text)}

geckoEditor.isDocReady = function() {return true;}

geckoEditor.reloadOnDesignMode=false;

geckoEditor.initContent = function(doc,content){
	if (content) doc.execCommand(&quot;insertHTML&quot;,false,geckoEditor.preProcessor(content));
}

// INTERNET EXPLORER BROWSER SPECIFIC METHODS
	
IEeditor.setupFrame = function(iframe,height,callback) {
	iframe.width=&quot;99%&quot;;  //IE displays the iframe at the bottom if 100%. CSS layout problem ? I don't know. To be studied...
	iframe.height=height.toString();
	iframe.attachEvent(&quot;onreadystatechange&quot;,callback);
}

IEeditor.plugEvents = function(doc,onchange){
	doc.attachEvent(&quot;onkeyup&quot;, onchange);
	doc.attachEvent(&quot;onkeydown&quot;, onchange);
	doc.attachEvent(&quot;onclick&quot;, onchange);
}

IEeditor.isDocReady = function(doc){
	if (doc.readyState!=&quot;complete&quot;) return false;
	if (!doc.body) return false;
	return (doc &amp;&amp; doc.getElementsByTagName &amp;&amp; doc.getElementsByTagName(&quot;head&quot;) &amp;&amp; doc.getElementsByTagName(&quot;head&quot;).length&gt;0);
}

IEeditor.postProcessor = function(text){return text};

IEeditor.preProcessor = function(text){return easyEditor.SimplePreProcessoror(text)}

IEeditor.reloadOnDesignMode=true;

IEeditor.initContent = function(doc,content){
	if (content) doc.body.innerHTML=IEeditor.preProcessor(content);
}
	
function contextualCallback(obj,func){
    return function(){return func.call(obj)}
}
	
Story.prototype.previousGatherSaveEasyEdit = Story.prototype.previousGatherSaveEasyEdit ? Story.prototype.previousGatherSaveEasyEdit : Story.prototype.gatherSaveFields; // to avoid looping if this line is called several times
Story.prototype.gatherSaveFields = function(e,fields){
	if(e &amp;&amp; e.getAttribute) {
		var f = e.getAttribute(&quot;easyEdit&quot;);
		if(f){
			var newVal = config.macros.easyEdit.gather(e);
			if (newVal) fields[f] = newVal;
		}
		this.previousGatherSaveEasyEdit(e, fields);
	}
}

config.commands.easyEdit={
	text: &quot;write&quot;,
	tooltip: &quot;Edit this tiddler in wysiwyg mode&quot;,
	readOnlyText: &quot;view&quot;,
	readOnlyTooltip: &quot;View the source of this tiddler&quot;,
	handler : function(event,src,title) {
		clearMessage();
		var tiddlerElem = document.getElementById(story.idPrefix + title);
		var fields = tiddlerElem.getAttribute(&quot;tiddlyFields&quot;);
		story.displayTiddler(null,title,&quot;EasyEditTemplate&quot;,false,null,fields);
		return false;
	}
}

config.shadowTiddlers.ViewTemplate = config.shadowTiddlers.ViewTemplate.replace(/\+editTiddler/,&quot;+editTiddler easyEdit&quot;);

config.shadowTiddlers.EasyEditTemplate = config.shadowTiddlers.EditTemplate.replace(/macro='edit text'/,&quot;macro='easyEdit text'&quot;);

config.shadowTiddlers.EasyEditToolBarStyleSheet = &quot;/*{{{*/\n&quot;;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar {font-size:0.8em}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.editor iframe {border:1px solid #DDD}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar td{border:1px solid #888; padding:2px 1px 2px 1px; vertical-align:middle}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar td.separator{border:0}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .button{border:0;color:#444}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .buttonON{background-color:#EEE}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar {margin:0.25em 0}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .boldButton {font-weight:bold}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .italicButton .button {font-style:italic;padding-right:0.65em}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .underlineButton .button {text-decoration:underline}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .strikeButton .button {text-decoration:line-through}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .unorderedListButton {margin-left:0.7em}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .justifyleftButton .button {padding-left:0.1em}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .justifyrightButton .button {padding-right:0.1em}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .justifyfullButton .button, .easyEditorToolBar .indentButton .button, .easyEditorToolBar .outdentButton .button {padding-left:0.1em;padding-right:0.1em}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .increasefontsizeButton .button {padding-left:0.15em;padding-right:0.15em; font-size:1.3em; line-height:0.75em}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .decreasefontsizeButton .button {padding-left:0.4em;padding-right:0.4em; font-size:0.8em;}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .forecolorButton .button {color:red;}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;.easyEditorToolBar .fontnameButton .button {font-family:serif}\n&quot; ;
config.shadowTiddlers.EasyEditToolBarStyleSheet +=&quot;/*}}}*/&quot;;

store.addNotification(&quot;EasyEditToolBarStyleSheet&quot;, refreshStyles); 

config.shadowTiddlers.EasyEditDocStyleSheet = &quot;/*{{{*/\n \n/*}}}*/&quot;;
if (config.annotations) config.annotations.EasyEditDocStyleSheet = &quot;This stylesheet is applied when editing a text with the wysiwyg easyEditor&quot;;

//}}}
/***
!Link button add-on
***/
//{{{
EditorToolbar.createLinkButton = function(place,name) {
	this.elements[name] = createTiddlyButton(place,EditorToolbar.buttons[name].label,EditorToolbar.buttons[name].toolTip,contextualCallback(this,EditorToolbar.onInputLink()),&quot;button&quot;);
}

EditorToolbar.onInputLink = function() {
	return function(){
		var browser = config.browser.isGecko ? geckoEditor : (config.browser.isIE ? IEeditor : null);
		var value = browser ? browser.getLink(this.target) : &quot;&quot;;
		value = prompt(EditorToolbar.buttons[&quot;createlink&quot;].prompt,value);
		if (value) browser.doLink(this.target,value);
		else if (value==&quot;&quot;) this.target.execCommand(&quot;unlink&quot;, false, value);
		EditorToolbar.onUpdateButton.call(this);
		return false;
	}
}

EditorToolbar.buttonsList += &quot;,separator,createlink&quot;;

EditorToolbar.buttons.createlink = {onCreate : EditorToolbar.createLinkButton, label:&quot;L&quot;, toolTip : &quot;Set link&quot;, prompt: &quot;Enter link url&quot;};


geckoEditor.getLink=function(doc){
	var range=doc.defaultView.getSelection().getRangeAt(0);
	var container = range.commonAncestorContainer;
	var node = (container.nodeType==3) ? container.parentNode : range.startContainer.childNodes[range.startOffset];
	if (node &amp;&amp; node.tagName==&quot;A&quot;) {
		var r=doc.createRange();
		r.selectNode(node);
		doc.defaultView.getSelection().addRange(r);
		return (node.getAttribute(&quot;tiddler&quot;) ? &quot;#&quot;+node.getAttribute(&quot;tiddler&quot;) : node.href);
	}
	else return (container.nodeType==3 ? &quot;#&quot;+container.textContent.substr(range.startOffset, range.endOffset-range.startOffset).replace(/ $/,&quot;&quot;) : &quot;&quot;);
}

geckoEditor.doLink=function(doc,link){ // store tiddler in a temporary attribute to avoid url encoding of tiddler's name
	var pin = &quot;href&quot;+Math.random().toString().substr(3);
	doc.execCommand(&quot;createlink&quot;, false, pin);
	var isTiddler=(link.charAt(0)==&quot;#&quot;);
	var node = doc.defaultView.getSelection().getRangeAt(0).commonAncestorContainer;
	var links= (node.nodeType!=3) ? node.getElementsByTagName(&quot;a&quot;) : [node.parentNode];
	for (var cpt=0;cpt&lt;links.length;cpt++) 
			if (links[cpt].href==pin){
				links[cpt].href=isTiddler ? &quot;javascript:;&quot; : link; 
				links[cpt].setAttribute(&quot;tiddler&quot;,isTiddler ? link.substr(1) : &quot;&quot;);
			}
}

geckoEditor.beforeLinkPostProcessor = geckoEditor.beforelinkPostProcessor ? geckoEditor.beforelinkPostProcessor : geckoEditor.postProcessor;
geckoEditor.postProcessor = function(text){
	return geckoEditor.beforeLinkPostProcessor(text).replace(/&lt;a tiddler=&quot;([^&quot;]*)&quot; href=&quot;javascript:;&quot;&gt;(.*?)(?:&lt;\/a&gt;)/gi,&quot;[[$2|$1]]&quot;).replace(/&lt;a tiddler=&quot;&quot; href=&quot;/gi,'&lt;a href=&quot;');
}

geckoEditor.beforeLinkPreProcessor = geckoEditor.beforeLinkPreProcessor ? geckoEditor.beforeLinkPreProcessor : geckoEditor.preProcessor
geckoEditor.preProcessor = function(text){
	return geckoEditor.beforeLinkPreProcessor(text).replace(/\[\[([^|\]]*)\|([^\]]*)]]/g,'&lt;a tiddler=&quot;$2&quot; href=&quot;javascript:;&quot;&gt;$1&lt;/a&gt;');
}


IEeditor.getLink=function(doc){
	var node=doc.selection.createRange().parentElement();
	if (node.tagName==&quot;A&quot;) return node.href;
	else return (doc.selection.type==&quot;Text&quot;? &quot;#&quot;+doc.selection.createRange().text.replace(/ $/,&quot;&quot;) :&quot;&quot;);
}

IEeditor.doLink=function(doc,link){
	doc.execCommand(&quot;createlink&quot;, false, link);
}

IEeditor.beforeLinkPreProcessor = IEeditor.beforeLinkPreProcessor ? IEeditor.beforeLinkPreProcessor : IEeditor.preProcessor
IEeditor.preProcessor = function(text){
	return IEeditor.beforeLinkPreProcessor(text).replace(/\[\[([^|\]]*)\|([^\]]*)]]/g,'&lt;a ref=&quot;#$2&quot;&gt;$1&lt;/a&gt;');
}

IEeditor.beforeLinkPostProcessor = IEeditor.beforelinkPostProcessor ? IEeditor.beforelinkPostProcessor : IEeditor.postProcessor;
IEeditor.postProcessor = function(text){
	return IEeditor.beforeLinkPostProcessor(text).replace(/&lt;a href=&quot;#([^&gt;]*)&quot;&gt;([^&lt;]*)&lt;\/a&gt;/gi,&quot;[[$2|$1]]&quot;);
}

IEeditor.beforeLinkInitContent = IEeditor.beforeLinkInitContent ? IEeditor.beforeLinkInitContent : IEeditor.initContent;
IEeditor.initContent = function(doc,content){
	IEeditor.beforeLinkInitContent(doc,content);
	var links=doc.body.getElementsByTagName(&quot;A&quot;);
	for (var cpt=0; cpt&lt;links.length; cpt++) {
		links[cpt].href=links[cpt].ref; //to avoid IE conversion of relative URLs to absolute
		links[cpt].removeAttribute(&quot;ref&quot;);	
	}
}

config.shadowTiddlers.EasyEditToolBarStyleSheet += &quot;\n/*{{{*/\n.easyEditorToolBar .createlinkButton .button {color:blue;text-decoration:underline;}\n/*}}}*/&quot;;

config.shadowTiddlers.EasyEditDocStyleSheet += &quot;\n/*{{{*/\na {color:#0044BB;font-weight:bold}\n/*}}}*/&quot;;

//}}}</pre>
</div>
<div title="EncryptedVaultPlugin" modifier="Pascal" created="200711262147" modified="200712211731" tags="VisualTW systemConfig Tools" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712211731" label="EncryptedVault">
<pre>/***
|''Name:''|EncryptedVaultPlugin|
|''Description:''|Adds RC4 encryption and password protection to tiddywiki.|
|''Version:''|1.0.1|
|''Date:''|Dec 21,2007|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.2.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0, others|
!Description
*Create an ''encrypted vault'' where all tiddlers are ''password protected''. 
*By default, only the system tiddlers aren't encrypted.
*Even shadow tiddlers (MainMenu, SiteTitle, PageTemplate, StyleSheet, ...) ''can be encrypted''. The shadow version is used until unlocking.
!Demo
Use &lt;&lt;unlock&gt;&gt; button on a protected wiki. By example : http://visualtw.ouvaton.org/demo/EncryptedVaultPlugin.html
!Installation
#Import the plugin (tagged as systemConfig)
#Save and reload
#Save once more time to create the encrypted vault
#Reload and set a password
!Usage
*Use &lt;&lt;unlock&gt;&gt;&lt;&lt;setPassword&gt;&gt; button (available by default in SideBarOptions)
*Use a blank password to save unencrypted (disable vault usage)
*Use {{{unencrypted}}} tag to avoid encryption for some tiddler
*Use {{{forceEncryption}}} tag to force some shadow tiddler to be encrypted
!Configuration
The following macros are available :
*{{{&lt;&lt;unlock ButtonTitle ButtonTooltip OpenTiddlersWhenUnlock CloseTiddlersWhenUnlock&gt;&gt;}}} creates a button to unlock the encrypted vault (all parameters are optionnal)
*{{{&lt;&lt;setPassword ButtonTitle ButtonTooltip&gt;&gt;}}} if unlocked, creates a button to set the current password (all parameters are optionnal)
*{{{&lt;&lt;purge ButtonTitle ButtonTooltip&gt;&gt;}}} if locked, creates a button to purge a locked vault, useful for lost password (encrypted content is the deleted)
*{{{&lt;&lt;ifLocked tiddlyText&gt;&gt;}}} displays tiddlyText (wikified) if the vault is locked
*{{{&lt;&lt;ifUnlocked tiddlyText&gt;&gt;}}} displays tiddlyText (wikified) if the vault is unlocked
&lt;&lt;ifLocked &quot;!!!!Lost password ?&quot;&gt;&gt;&lt;&lt;ifLocked &quot;Click on&quot;&gt;&gt; &lt;&lt;purge&gt;&gt;&lt;&lt;ifLocked &quot;to delete any content locked in the encrypted vault.&quot;&gt;&gt;
***/
//{{{

config.messages.vaultCreationInfo = &quot;The encrypted vault has been created&quot;;
config.messages.purgeConfirm = &quot;Purge the encrypted vault ?\n\nAll unlocked content will be lost.&quot;;
config.messages.vaultPurgedInfo = &quot;All contents have been purged from encrypted vault.\nPassword has been blanked.\nYou must save once to apply this changes.&quot;;
config.messages.vaultEncryptedInfo = &quot;Saving with encryption&quot;;
config.messages.vaultUnchangedInfo = &quot;No changes in Encrypted vault&quot;;
config.messages.noLockedVaultWarning = &quot;Unable to proceed. No locked encrypted vault.&quot;;
config.messages.emptyVaultInfo = &quot;Saving without encryption&quot;;
config.messages.saveWithLockedVaultConfirm = &quot;Encrypted vault is locked. No changes will apply inside.\n\nAre you sure ?&quot;;
config.messages.confirmOverload = &quot;This following tiddler already exists in system store. Overload ?\nOK : the encrypted version will replace the system store version\nCancel : the system store version will replace the encrypted version&quot;;

SaverBase.systemStore=&quot;unencrypted&quot;;
SaverBase.vault=&quot;forceEncryption&quot;;

var startSaveVaultArea = '&lt;div id=&quot;' + 'vaultArea&quot;&gt;'; // Split up into two so that indexOf() of this source doesn't find it
var endSaveVaultArea = '&lt;/d' + 'iv&gt;';

config.shadowTiddlers.SideBarOptions = config.shadowTiddlers.SideBarOptions.replace(/&lt;&lt;saveChanges&gt;&gt;/,&quot;&lt;&lt;unlock&gt;&gt;&lt;&lt;setPassword&gt;&gt;&lt;&lt;saveChanges&gt;&gt;&quot;);
config.shadowTiddlers.GettingStarted+=&quot;\n\n&lt;&lt;ifLocked 'This TiddlyWiki use EncryptedVaultPlugin. To load protected content click on'&gt;&gt;&lt;&lt;unlock&gt;&gt;&lt;&lt;ifUnlocked 'This TiddlyWiki use EncryptedVaultPlugin. To set or change password click on'&gt;&gt;&lt;&lt;setPassword&gt;&gt;&quot;

window.updateOriginal= function(original,posDiv)	// overriding the TW2.2 standard function
{
	var vaultIsUpdatable = (!locateVaultArea(original) || !vault.isLocked() || vault.purge);  // vault is new, unlocked or must be purged
	
	if(!posDiv)
		posDiv = locateStoreArea(original);
	if(!posDiv) {
		alert(config.messages.invalidFileError.format([localPath]));
		return null;
	}
	var revised = original.substr(0,posDiv[0] + startSaveArea.length) + &quot;\n&quot; +
				convertUnicodeToUTF8((vaultIsUpdatable &amp;&amp; vault.password) ? store.allUnencryptedTiddlersAsHtml() : store.allTiddlersAsHtml())  + &quot;\n&quot; +
				original.substr(posDiv[1]);
				
	if (vaultIsUpdatable) {
		posVault = locateVaultArea(original)
		if(!posVault) {
			revised=createVault(revised);
			posVault = locateVaultArea(revised);
			if(!posVault) {
				alert(config.messages.invalidFileError.format([localPath]));
				return;
			}
		}
		var revised = revised.substr(0,posVault[0] + startSaveVaultArea.length) +
					convertUnicodeToUTF8(vault.password ? vault.encrypt(store.allEncryptedTiddlersAsHtml()) : &quot;&quot;) +
					revised.substr(posVault[1]);
		if (vault.password) displayMessage(config.messages.vaultEncryptedInfo);
		else displayMessage(config.messages.emptyVaultInfo);
	}
	else displayMessage(config.messages.vaultUnchangedInfo);
	
	var newSiteTitle = convertUnicodeToUTF8(getPageTitle()).htmlEncode();
	revised = revised.replaceChunk(&quot;&lt;title&quot;+&quot;&gt;&quot;,&quot;&lt;/title&quot;+&quot;&gt;&quot;,&quot; &quot; + newSiteTitle + &quot; &quot;);
	revised = updateLanguageAttribute(revised);
	revised = updateMarkupBlock(revised,&quot;PRE-HEAD&quot;,&quot;MarkupPreHead&quot;);
	revised = updateMarkupBlock(revised,&quot;POST-HEAD&quot;,&quot;MarkupPostHead&quot;);
	revised = updateMarkupBlock(revised,&quot;PRE-BODY&quot;,&quot;MarkupPreBody&quot;);
	revised = updateMarkupBlock(revised,&quot;POST-SCRIPT&quot;,&quot;MarkupPostBody&quot;);
	return revised;
}

function createVault(original) {
	var revised=original.replace(/&lt;!--POST-SHADOWAREA--&gt;/,'&lt;!--POST-SHADOWAREA--&gt;\n&lt;div id=&quot;vaultArea&quot;&gt;&lt;/div&gt;\n&lt;!--POST-VAULTAREA--&gt;');
	var vaultStyles = '&lt;!--PRE-VAULTSTYLE-START--&gt;\n&lt;style type=&quot;text/css&quot;&gt;\n#vaultArea {display:none;}\n#vaultArea div {padding:0.5em; margin:1em 0em 0em 0em; border-color:#fff #666 #444 #ddd; border-style:solid; border-width:2px; overflow:auto;}\n&lt;/style&gt;\n&lt;!--PRE-VAULTSTYLE-END--&gt;\n';
	if (revised.search(&quot;&lt;!--PRE-VAULTSTYLE-START--&gt;&quot;)&lt;0) var revised=revised.replace(/&lt;!--POST-HEAD-START--&gt;/,vaultStyles +'&lt;!--POST-HEAD-START--&gt;');
	alert(config.messages.vaultCreationInfo);
	return revised;
}

function locateVaultArea(original)  //cloned from the TW2.2 standard function
{
	// Locate the vaultArea div's. Should be just before the storeArea div
	var posOpeningDiv = original.indexOf(startSaveVaultArea);
	var limitClosingDiv = original.indexOf(&quot;&lt;&quot;+&quot;!--POST-VAULTAREA--&quot;+&quot;&gt;&quot;);
	if(limitClosingDiv == -1)
		limitClosingDiv = original.indexOf(&quot;&lt;div id=&quot;+'&quot;storeArea&quot;'+&quot;&gt;&quot;);
	var posClosingDiv = original.lastIndexOf(endSaveVaultArea,limitClosingDiv);
	return (posOpeningDiv != -1 &amp;&amp; posClosingDiv != -1) ? [posOpeningDiv,posClosingDiv] : null;
}

TiddlyWiki.prototype.allUnencryptedTiddlersAsHtml = function() {
	return store.getSaver().externalize(store, SaverBase.systemStore);
};

TiddlyWiki.prototype.allEncryptedTiddlersAsHtml = function() {
	return store.getSaver().externalize(store, SaverBase.vault);
};

SaverBase.prototype.externalize = function(store, tiddlerType) // overriding the TW2.2 standard function
{
	var results = [];
	var tiddlers = store.getTiddlers(&quot;title&quot;);
	for(var t = 0; t &lt; tiddlers.length; t++)
		if (!tiddlerType || (this.getTiddlerType(tiddlers[t]) == tiddlerType))	// this line was changed from standard function
			results.push(this.externalizeTiddler(store,tiddlers[t]));
	return results.join(&quot;\n&quot;);
};

SaverBase.prototype.getTiddlerType= function(tiddler) {
	if (tiddler.isTagged(SaverBase.vault)) return SaverBase.vault;
	if (store.isShadowTiddler([tiddler.title])) return SaverBase.systemStore;
	if (tiddler.isTagged(&quot;systemConfig&quot;)||tiddler.isTagged(SaverBase.systemStore)) return SaverBase.systemStore;
	return SaverBase.vault;
};

LoaderBase.prototype.loadTiddler = function(store,node,tiddlers) // overriding the TW2.2 standard function
{
	var title = this.getTitle(store,node);
	if (store.getTiddler(title) &amp;&amp; !confirm(config.messages.confirmOverload+&quot;\n\n&quot;+title)) // this line was changed from standard function
		return;	
	if(title) {
		var tiddler = store.createTiddler(title);
		this.internalizeTiddler(store,tiddler,title,node);
		tiddlers.push(tiddler);
	}
};

window.saveChanges_noVault = window.saveChanges;
window.saveChanges= function(onlyIfDirty,tiddlers){
	if (!vault.isLocked() || vault.purge || !vault.exists() || (vault.isLocked() &amp;&amp; confirm(config.messages.saveWithLockedVaultConfirm)))
		saveChanges_noVault(onlyIfDirty,tiddlers);
}

vault = {
	load : function(){
		if (!vault.isLocked()) {
			alert(config.messages.vaultAlreadyUnlockedWarning);
			return false;
		}
		else {
			var storeElem = document.getElementById(&quot;vaultArea&quot;);
			if (storeElem) {
				var src = storeElem.innerHTML;
				var pwd = vault.password ? vault.password : &quot;&quot;;
				while ((vault.isEncrypted(src)) &amp;&amp; (pwd!=null)) {
					if (pwd) src = vault.decrypt(src, pwd);
					if (vault.isEncrypted(src)) pwd = prompt(vault.prompt,pwd);
				}
				if (pwd!=null) vault.password = pwd;
				if (!vault.isEncrypted(src)) {
					var wasDirty = store.isDirty();
					var e = document.createElement(&quot;div&quot;);
					e.innerHTML=src;
					if (src) store.getLoader().loadTiddlers(store,e.childNodes);
					vault.loaded = true;
					refreshAll();
					story.refreshAllTiddlers();
					store.setDirty(wasDirty);
					return true;
				}
				else return false;
			}
		}
	},
	decrypt : function(src,pwd){
		var res = Crypto.cryptomx.decrypt(pwd,src.substr(vault.prefix.length));
		return res  ? res : src;
	},
	isEncrypted : function(src) {
		return (src.substr(0,vault.prefix.length) == vault.prefix);
	},
	encrypt : function(src){
		return vault.password ? vault.prefix + Crypto.cryptomx.encrypt(vault.password,src) : src;
	},
	isLocked : function(){
		if (vault.loaded) return false;
		var storeElem = document.getElementById(&quot;vaultArea&quot;);
		return (!storeElem || (storeElem &amp;&amp; vault.isEncrypted(storeElem.innerHTML)));
	},
	exists : function() {
		return (document.getElementById(&quot;vaultArea&quot;)!=null);
	},
	prefix : &quot;Cryptomx@&quot;,
	prompt : &quot;Enter a password&quot;,
	loaded : false,
	purge : false
}

config.macros.unlock = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		var label = params[0] ? params[0] : &quot;unlock vault&quot;;
		var tooltip = params[1] ? params[1] : &quot;unlock encrypted vault&quot;;
		var openTiddlers = params[2] ? params[2] : &quot;&quot;;
		var closeTiddlers = params[3] ? params[3] : &quot;&quot;;
		if (vault.isLocked() &amp;&amp; vault.exists()) {
			var btn = createTiddlyButton(place,label, tooltip,this.onClick);
			btn.setAttribute(&quot;openTiddlers&quot;,openTiddlers);
			btn.setAttribute(&quot;closeTiddlers&quot;,closeTiddlers);
		}
	},
    onClick:function(){
		var openTiddlers = this.getAttribute(&quot;openTiddlers&quot;);
		var closeTiddlers = this.getAttribute(&quot;closeTiddlers&quot;);
		if (vault.load()) {
			if (closeTiddlers) {
				var tiddlers = store.filterTiddlers(closeTiddlers);
				for(var t=0; t&lt;tiddlers.length; t++) {
					var elem = document.getElementById(story.idPrefix + tiddlers[t].title);
					if (elem &amp;&amp; elem.getAttribute(&quot;dirty&quot;)!=&quot;true&quot;)
						story.closeTiddler(tiddlers[t].title);
				}
			}
			if (openTiddlers) {
				var tiddlers = store.filterTiddlers(openTiddlers);
				for(var t=0; t&lt;tiddlers.length; t++)
					story.displayTiddler(&quot;bottom&quot;,tiddlers[t].title);
			}
		}
		return false;
	}
}

config.macros.setPassword = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		var label = params[0] ? params[0] : &quot;set password&quot;;
		var tooltip = params[1] ? params[1] : &quot;Set password for encrypted vault&quot;;
		if (!vault.isLocked()) createTiddlyButton(place, label, tooltip,this.onClick);
	},
    onClick:function(){
		var pwd = prompt(vault.prompt,(vault.password ? vault.password : &quot;&quot;));
		if (pwd != null) vault.password = pwd;
		return false;
	}
}

config.macros.purge = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		var label = params[0] ? params[0] : &quot;purge vault&quot;;
		var tooltip = params[1] ? params[1] : &quot;Delete locked vault&quot;;
		if (vault.isLocked() &amp;&amp; vault.exists()) createTiddlyButton(place,label, tooltip,this.onClick);
	},
    onClick:function(){
		if (!vault.isLocked())
			alert(config.messages.noLockedVaultWarning);
		else
			if (confirm(config.messages.purgeConfirm)) {
				vault.purge=true;
				alert(config.messages.vaultPurgedInfo);
			}
		return false;
	}
}

config.macros.ifLocked = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		if (vault.isLocked() &amp;&amp; vault.exists()) wikify(params[0],place,null,tiddler);
	}
}

config.macros.ifUnlocked = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		if (!vault.isLocked()) wikify(params[0],place,null,tiddler);
	}
}

//}}}


/***
Cryptomx code from http://cryptomx.sourceforge.net
***/
//{{{
Crypto.cryptomx = {
	dg :'',
	makeArray: function(n) {
		for (var i=1; i&lt;=n; i++) {
			this[i]=0
		}
		return this
	},
	rc4: function(key, text) {
		var i, x, y, t, x2;
		this.status(&quot;rc4&quot;)
		s=this.makeArray(0);
		
		for (i=0; i&lt;256; i++) {
			s[i]=i
		}
		y=0
		for (x=0; x&lt;256; x++) {
			y=(key.charCodeAt(x % key.length) + s[x] + y) % 256
			t=s[x]; s[x]=s[y]; s[y]=t
		}
		x=0;  y=0;
		var z=&quot;&quot;
		for (x=0; x&lt;text.length; x++) {
			x2=x % 256
			y=( s[x2] + y) % 256
			t=s[x2]; s[x2]=s[y]; s[y]=t
			z+= String.fromCharCode((text.charCodeAt(x) ^ s[(s[x2] + s[y]) % 256]))
		}
		return z
	},
	badd: function(a,b) { // binary add
		var r=''
		var c=0
		while(a || b) {
			c=this.chop(a)+this.chop(b)+c
			a=a.slice(0,-1); b=b.slice(0,-1)
			if(c &amp; 1) {
				r=&quot;1&quot;+r
			} else {
				r=&quot;0&quot;+r
			}
			c&gt;&gt;=1
		}
		if(c) {r=&quot;1&quot;+r}
		return r
	},
	chop:function(a) {
		if(a.length) {
			return parseInt(a.charAt(a.length-1))
		} else {
			return 0
		}
	},
	bsub:function(a,b) { // binary subtract
		var r=''
		var c=0
		while(a) {
			c=this.chop(a)-this.chop(b)-c
			a=a.slice(0,-1); b=b.slice(0,-1)
			if(c==0) {
				r=&quot;0&quot;+r
			}
			if(c == 1) {
				r=&quot;1&quot;+r
				c=0
			}
			if(c == -1) {
				r=&quot;1&quot;+r
				c=1
			}
			if(c==-2) {
				r=&quot;0&quot;+r
				c=1
			}
		}
		if(b || c) {return ''}
		return this.bnorm(r)
	},
	bnorm:function(r) { // trim off leading 0s
		var i=r.indexOf('1')
		if(i == -1) {
			return '0'
		} else {
			return r.substr(i)
		}
	},
	bmul:function(a,b) { // binary multiply
		var r=''; var p=''
		while(a) {
			if(this.chop(a) == '1') {
				r=this.badd(r,b+p)
			}
			a=a.slice(0,-1)
			p+='0'
		}
		return r;
	},
	bmod:function(a,m) { // binary modulo
		return this.bdiv(a,m).mod
	},
	bdiv:function(a,m) { // binary divide &amp; modulo
		// this.q = quotient this.mod=remainder
		var lm=m.length, al=a.length
		var p='',d
		this.q=''
		for(n=0; n&lt;al; n++) {
			p=p+a.charAt(n);
			if(p.length&lt;lm || (d=this.bsub(p,m)) == '') {
				this.q+='0'
			} else {
				if(this.q.charAt(0)=='0') {
					this.q='1'
				} else {
					this.q+=&quot;1&quot;
				}
				p=d
			}
		}
		this.mod=this.bnorm(p)
		return this
	},
	bmodexp:function(x,y,m) { // binary modular exponentiation
		var r='1'
		this.status(&quot;bmodexp &quot;+x+&quot; &quot;+y+&quot; &quot;+m)
		
		while(y) {
			if(this.chop(y) == 1) {
				r=this.bmod(this.bmul(r,x),m)
			}
			y=y.slice(0,y.length-1)
			x=this.bmod(this.bmul(x,x),m)
		}
		return this.bnorm(r)
	},
	modexp:function(x,y,m) { // modular exponentiation
		// convert packed bits (text) into strings of 0s and 1s
		return this.b2t(this.bmodexp(this.t2b(x),this.t2b(y),this.t2b(m)))
	},
	i2b: function(i) { // convert integer to binary
		var r=''
		while(i) {
			if(i &amp; 1) { r=&quot;1&quot;+r} else {r=&quot;0&quot;+r}
			i&gt;&gt;=1;
		}
		return r? r:'0'
	},
	t2b:function(s) {
		var r=''
		if(s=='') {return '0'}
		while(s.length) {
			var i=s.charCodeAt(0)
			s=s.substr(1)
			for(n=0; n&lt;8; n++) {
				r=((i &amp; 1)? '1':'0') + r
				i&gt;&gt;=1;
			}
		}
		return this.bnorm(r)
	},
	b2t:function(b) {
		var r=''; var v=0; var m=1
		while(b.length) {
			v|=this.chop(b)*m
			b=b.slice(0,-1)
			m&lt;&lt;=1
			if(m==256 || b=='') {
				r+=String.fromCharCode(v)
				v=0; m=1
			}
		}
		return r
	},
	b64s:'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_&quot;',
	textToBase64:function(t) {
		this.status(&quot;t 2 b64&quot;)
		var r=''; var m=0; var a=0; var tl=t.length-1; var c
		for(n=0; n&lt;=tl; n++) {
			c=t.charCodeAt(n)
			r+=this.b64s.charAt((c &lt;&lt; m | a) &amp; 63)
			a = c &gt;&gt; (6-m)
			m+=2
			if(m==6 || n==tl) {
				r+=this.b64s.charAt(a)
				if((n%45)==44) {r+=&quot;\n&quot;}
				m=0
				a=0
			}
		}
		return r
	},
	base64ToText:function(t) {
		this.status(&quot;b64 2 t&quot;)
		var r=''; var m=0; var a=0; var c
		for(n=0; n&lt;t.length; n++) {
			c=this.b64s.indexOf(t.charAt(n))
			if(c &gt;= 0) {
				if(m) {
					r+=String.fromCharCode((c &lt;&lt; (8-m))&amp;255 | a)
				}
				a = c &gt;&gt; m
				m+=2
				if(m==8) { m=0 }
			}
		}
		return r
	},

	rand:function(n) {  return Math.floor(Math.random() * n) },
	rstring:function(s,l) {
		var r=&quot;&quot;
		var sl=s.length
		while(l&gt;0) {
			l=l-1;
			r+=s.charAt(rand(sl))
		}
		//status(&quot;rstring &quot;+r)
		return r
	},
	key2:function(k) {
		var l=k.length
		var kl=l
		var r=''
		while(l--) {
			r+=k.charAt((l*3)%kl)
		}
		return r
	},
	rsaEncrypt:function(keylen,key,mod,text) {
		// I read that rc4 with keys larger than 256 bytes doesn't significantly
		// increase the level of rc4 encryption because it's sbuffer is 256 bytes
		// makes sense to me, but what do i know...

		this.status(&quot;encrypt&quot;)
		if(text.length &gt;= keylen) {
			var sessionkey=this.rc4(rstring(text,keylen),rstring(text,keylen))

			// session key must be less than mod, so mod it
			sessionkey=this.b2t(bmod(t2b(sessionkey),t2b(mod)))
			alert(&quot;sessionkey=&quot;+sessionkey)

			// return the rsa encoded key and the encrypted text
			// i'm double encrypting because it would seem to me to
			// lessen known-plaintext attacks, but what do i know
			return this.modexp(sessionkey,key,mod) +
			this.rc4(this.key2(sessionkey),this.rc4(sessionkey,text))
		} else {

			// don't need a session key
			return this.modexp(text,key,mod)
		}
	},
	rsaDecrypt:function(keylen,key,mod,text) {
		this.status(&quot;decrypt&quot;)
		if(text.length &lt;= keylen) {
			return this.modexp(text,key,mod)
		} else {

			// sessionkey is first keylen bytes
			var sessionkey=text.substr(0,keylen)
			text=text.substr(keylen)

			// un-rsa the session key
			sessionkey=this.modexp(sessionkey,key,mod)
			alert(&quot;sessionkey=&quot;+sessionkey)

			// double decrypt the text
			return this.rc4(sessionkey,this.rc4(this.key2(sessionkey,text),text))
		}
	},
	trim2:function(d) { return d.substr(0,d.lastIndexOf('1')+1) },
	bgcd:function(u,v) { // return greatest common divisor
		// algorythm from http://algo.inria.fr/banderier/Seminar/Vallee/index.html
		var d, t
		while(1) {
			d=this.bsub(v,u)
			//alert(v+&quot; - &quot;+u+&quot; = &quot;+d)
			if(d=='0') {return u}
			if(d) {
				if(d.substr(-1)=='0') {
					v=d.substr(0,d.lastIndexOf('1')+1) // v=(v-u)/2^val2(v-u)
				} else v=d
			} else {
				t=v; v=u; u=t // swap u and v
			}
		}
	},

	isPrime:function(p) {
		var n,p1,p12,t
		p1=this.bsub(p,'1')
		t=p1.length-p1.lastIndexOf('1')
		p12=this.trim2(p1)
		for(n=0; n&lt;2; n+=this.mrtest(p,p1,p12,t)) {
			if(n&lt;0) return 0
		}
		return 1
	},
	mrtest:function(p,p1,p12,t) {
		// Miller-Rabin test from forum.swathmore.edu/dr.math/
		var n,a,u
		a='1'+this.rstring('01',Math.floor(p.length/2)) // random a
		//alert(&quot;mrtest &quot;+p+&quot;, &quot;+p1+&quot;, &quot;+a+&quot;-&quot;+p12)
		u=this.bmodexp(a,p12,p)
		if(u=='1') {return 1}
		for(n=0;n&lt;t;n++) {
			u=this.bmod(this.bmul(u,u),p)
			//dg+=u+&quot; &quot;
			if(u=='1') return -100
			if(u==p1) return 1
		}
		return -100
	},
	pfactors:'11100011001110101111000110001101',
	// this number is 3*5*7*11*13*17*19*23*29*31*37
	prime:function(bits) {
		// return a prime number of bits length
		var p='1'+this.rstring('001',bits-2)+'1'
		while( ! this.isPrime(p)) {
			p=badd(p,'10'); // add 2
		}
		alert(&quot;p is &quot;+p)
		return p
	},
	genkey:function(bits) {
		q=prime(bits)
		do {
			p=q
			q=prime(bits)
		} while(bgcd(p,q)!='1')
		p1q1=this.bmul(this.bsub(p,'1'),this.bsub(q,'1'))
		// now we need a d, e,  and an n so that:
		//  p1q1*n-1=de  -&gt; bmod(bsub(bmul(d,e),'1'),p1q1)='0'
		// or more specifically an n so that d &amp; p1q1 are rel prime and factor e
		n='1'+this.rstring('001',Math.floor(bits/3)+2)
		alert('n is '+n)
		factorMe=this.badd(this.bmul(p1q1,n),'1')
		alert('factor is '+factorMe)
		//e=bgcd(factorMe,p1q1)
		//alert('bgcd='+e)
		e='1'
		// is this always 1?
		//r=bdiv(factorMe,e)
		//alert('r='+r.q+&quot; &quot;+r.mod)
		//if(r.mod != '0') {alert('Mod Error!')}
		//factorMe=r.q
		d=this.bgcd(factorMe,'11100011001110101111000110001101')
		alert('d='+d)
		if(d == '1' &amp;&amp; e == '1') {alert('Factoring failed '+factorMe+' p='+p+' q='+q)}
		e=this.bmul(e,d)
		r=this.bdiv(factorMe,d)
		d=r.q
		if(r.mod != '0') {alert('Mod Error 2!')}

		this.mod=this.b2t(bmul(p,q))
		this.pub=this.b2t(e)
		this.priv=this.b2t(d)
	},
	status:function(a) { },//alert(a)}
	encrypt:function(key,text) {
		return this.textToBase64(this.rc4(key,&quot;check:&quot;+text));
	},
	decrypt:function(key,text){
		var uncrypt = this.rc4(key,this.base64ToText(text));
		return (uncrypt.substr(0,6)==&quot;check:&quot;) ? uncrypt.substr(6) : null;
	}
}

//}}}</pre>
</div>
<div title="EncryptionDemo" modifier="Pascal" created="200712111637" modified="200712111701" tags="Demos" label="Encryption" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712111701">
<pre>[[EncryptedVaultPlugin]] demo is available [[here|http://visualtw.ouvaton.org/demo/EncryptedVaultPlugin.html]].</pre>
</div>
<div title="ExtendTagButtonPlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|ExtentTagButtonPlugin|
|Description:|Adds a New tiddler button in the tag drop down|
|Version:|3.2 ($Rev: 3861 $)|
|Date:|$Date: 2008-03-08 10:53:09 +1000 (Sat, 08 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#ExtendTagButtonPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License|http://mptw.tiddlyspot.com/#TheBSDLicense|
***/
//{{{

window.onClickTag_mptw_orig = window.onClickTag;
window.onClickTag = function(e) {
	window.onClickTag_mptw_orig.apply(this,arguments);
	var tag = this.getAttribute(&quot;tag&quot;);
	var title = this.getAttribute(&quot;tiddler&quot;);
	// Thanks Saq, you're a genius :)
	var popup = Popup.stack[Popup.stack.length-1].popup;
	createTiddlyElement(createTiddlyElement(popup,&quot;li&quot;,null,&quot;listBreak&quot;),&quot;div&quot;);
	wikify(&quot;&lt;&lt;newTiddler label:'New tiddler' tag:'&quot;+tag+&quot;'&gt;&gt;&quot;,createTiddlyElement(popup,&quot;li&quot;));
	return false;
}

//}}}

</pre>
</div>
<div title="ExternalizePlugin" modifier="Pascal" created="200712071539" modified="200712211727" tags="VisualTW systemConfig Wysiwyg" index="3" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712211727">
<pre>/***
|''Name:''|ExternalizePlugin|
|''Description:''|Edit tiddlers directly with your favorite external editor (html editor, text processor, javascript IDE, css editor, ...).|
|''Version:''|1.0.1|
|''Date:''|Dec 21,2007|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0|
!Installation
#install [[it's All Text!|https://addons.mozilla.org/fr/firefox/addon/4125]] Firefox extension.
#set up [[it's All Text!|https://addons.mozilla.org/fr/firefox/addon/4125]] options in its dialog box (see tips below).
#import this tiddler from [[homepage|http://visualtw.ouvaton.org/VisualTW.html]] (tagged as systemConfig).
#save and reload.
#set up hotkey below.
#use the &lt;&lt;toolbar externalize&gt;&gt; button in the tiddler's toolbar (in default ViewTemplate) or add {{{externalize}}} command in your own toolbar.
! Useful Addons
*[[HTMLFormattingPlugin|http://www.tiddlytools.com/#HTMLFormattingPlugin]] to embed wiki syntax in html tiddlers.&lt;&lt;br&gt;&gt;//__Tips__ : When this plugin is installed, you can use anchor syntax to link tiddlers in wysiwyg mode (example : #example). Anchors are converted back and from wiki syntax when editing.//
*[[TaggedTemplateTweak|http://www.TiddlyTools.com/#TaggedTemplateTweak]] to use alternative ViewTemplate/EditTemplate for tiddler's tagged with specific tag values.
!Configuration options 
|[[it's All Text!|https://addons.mozilla.org/fr/firefox/addon/4125]]  extension hotkey (copy/paste from the extension dialog box)|&lt;&lt;option txtExternalizeHotkey&gt;&gt;|
|Optional tiddler containing instructions to process the text before and after externalization&lt;&lt;br&gt;&gt;Example : [[ExternalizeAsHTML]]|&lt;&lt;option txtExternalizeProccessing&gt;&gt;|
|Template called by the {{{externalize}}} button|[[ExternalizeTemplate]]|
|Max waiting time for //It's All text!// to fire|&lt;&lt;option txtExternalizeMaxTime&gt;&gt;|
!//It's all text!// extension tips
*Tiddler text is edited with the first file extension
*Copy/paste Hot Key from the dialog box (with context menu)
*Edit button isn't necessary for the plugin (it uses hotkey)
*Try the extension configuration first, before trying it with the plugin.
!Code
***/
//{{{
config.options.txtExternalizeHotkey = config.options.txtExternalizeHotkey ? config.options.txtExternalizeHotkey : &quot;&quot;;
config.options.txtExternalizeProccessing = config.options.txtExternalizeProccessing ? config.options.txtExternalizeProccessing : &quot;&quot;;
config.options.txtExternalizeMaxTime = config.options.txtExternalizeMaxTime ? config.options.txtExternalizeMaxTime : &quot;30&quot;;

config.macros.externalize = {
	noExtensionError : &quot;It's all text ! extension wasn't available. Try to fire it manually with htokey or button. If it works, adapt your configuration (increase max waiting time or change hotkey) and try again.&quot;,
	hotKeyError : &quot;Hotkey wasn't understood. Use copy/paste from it's all text set up dialog.&quot;,
	EmptyHotKeyError : &quot;Hotkey isn't defined. Check ExternalizePlugin configuration.&quot;,
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		var field = params[0];
		var rows = params[1] || 0;
		var defVal = params[2] || '';
		if((tiddler instanceof Tiddler) &amp;&amp; field) {
			story.setDirty(tiddler.title,true);
			var e,v;
			var wrapper1 = createTiddlyElement(null,&quot;fieldset&quot;,null,&quot;fieldsetFix&quot;);
			var wrapper2 = createTiddlyElement(wrapper1,&quot;div&quot;);
			e = createTiddlyElement(wrapper2,&quot;textarea&quot;);
			e.setAttribute(&quot;readOnly&quot;,&quot;readOnly&quot;);
			v = config.macros.externalize.getValue(tiddler,field);
			v = v ? v : defVal;
			e.value = v;
			rows = rows ? rows : 10;
			var lines = v.match(/\n/mg);
			var maxLines = Math.max(parseInt(config.options.txtMaxEditRows),5);
			if(lines != null &amp;&amp; lines.length &gt; rows)
				rows = lines.length + 5;
			rows = Math.min(rows,maxLines);
			var id=tiddler.title+&quot;externalize&quot;+field;
			e.setAttribute(&quot;id&quot;,id);
			e.setAttribute(&quot;rows&quot;,rows);
			e.setAttribute(&quot;externalize&quot;,field);
			place.appendChild(wrapper1);
			config.macros.externalize.externalEdit(id);
			return e;
		}
	},
	externalEdit : function(id){
		window.setTimeout(function(){
			var element = document.getElementById(id);
			if (element) {
				var cpt=element.getAttribute(&quot;cpt&quot;);
				cpt = cpt ? cpt -1 : parseInt(config.options.txtExternalizeMaxTime);
				element.setAttribute(&quot;cpt&quot;,cpt);
				if (cpt&gt;0) {
					if (element.getAttribute(&quot;itsalltext_uid&quot;)) {
						element.dispatchEvent(config.macros.externalize.getKeyEvent());
						addClass(element,&quot;externalized&quot;);
					}
					else window.setTimeout(arguments.callee,100)
				}
				else alert(config.macros.externalize.noExtensionError);
			}
		},1000)
	},
	getKeyEvent : function(){
		var hotkey = config.options.txtExternalizeHotkey;
		if (hotkey) {
			var m = hotkey.match(/^(alt)?\s*(ctrl)?\s*(meta)?\s*(shift)?\s*(\w+)\s*$/i);
			if (m) {
				var ev = document.createEvent(&quot;KeyboardEvent&quot;);
				var cc = m[4]!=undefined ? m[5].toUpperCase() : m[5].toLowerCase();
				var charCode = m[5].length==1 ? cc.charCodeAt(0) : 0;
				var keyCode = m[5].length&gt;1 ? config.macros.externalize.keyMap[m[5]] : 0;
				ev.initKeyEvent(&quot;keypress&quot;,true,true,window,m[2]!=undefined,m[1]!=undefined,m[4]!=undefined,m[3]!=undefined,keyCode,charCode);
				return ev;
			}
			else alert(config.macros.externalize.hotKeyError);
		}
		else alert(config.macros.externalize.EmptyHotKeyError);
	},
	getValue : function(tiddler,field){
		var v = store.getValue(tiddler,field);
		v = v ? config.macros.externalize.textProcessing(v, &quot;Before&quot;) : &quot;&quot;;
		v = v.replace(/\[\[([^|\]]*)\|([^\]]*)]]/g,'&lt;a href=&quot;#$2&quot;&gt;$1&lt;/a&gt;');
		return v;
	},
	gather : function(e){
		return config.macros.externalize.textProcessing(e.value,&quot;After&quot;);
	},
	readParam : function(source,param){
		var re = new RegExp(&quot;^&quot;+ param +&quot;\\s*: *(.*)$&quot;,&quot;mg&quot;);
		var r = source &amp;&amp; re ? re.exec(source) : null;
		return r!=null ? r[1] : null;
	},
	textProcessing : function(text,key) {
		var params = config.options.txtExternalizeProccessing;
		var rexp = &quot;^\\[&quot;+key+&quot;\\] *(.*)\n(.*)\\n(.*)$&quot;;
		if (params) {
			var source = store.getTiddler(params);
			source = source ? source.text : config.shadowTiddlers[params];
			if (source) {
				var re=new RegExp(rexp,&quot;mg&quot;);
				var instructions = source.match(re);
				for(var cpt=0; cpt&lt;instructions.length; cpt++){
					re=new RegExp(rexp,&quot;mg&quot;);
					var res = re.exec(instructions[cpt]);
					text = text.replace(new RegExp(res[2],res[1]),res[3]); 
				}
			}
		}
		return text;	
	}
}

config.commands.externalize= {
	text: &quot;externalize&quot;,
	tooltip: &quot;Edit this tiddler with an external editor&quot;,
	handler : function(event,src,title) {
		clearMessage();
		var tiddlerElem = document.getElementById(story.idPrefix + title);
		var fields = tiddlerElem.getAttribute(&quot;tiddlyFields&quot;);
		story.displayTiddler(null,title,&quot;ExternalizeTemplate&quot;,false,null,fields);
		story.focusTiddler(title,&quot;text&quot;);
		return false;
	}
}

Story.prototype.previousGatherSaveExternalize = Story.prototype.previousGatherSaveExternalize ? Story.prototype.previousGatherSaveExternalize : Story.prototype.gatherSaveFields; // to avoid looping if this line is called several times
Story.prototype.gatherSaveFields = function(e,fields){
	if(e &amp;&amp; e.getAttribute) {
		var f = e.getAttribute(&quot;externalize&quot;);
		if(f){
			var newVal = config.macros.externalize.gather(e);
			if (newVal) fields[f] = newVal;
		}
		this.previousGatherSaveExternalize(e, fields);
	}
}

config.macros.externalize.keyMap = {
        'Backspace'   : 8,
        'Tab'   : 9,
        'Enter'	: 13,
        'Break'	: 19,
        'Escape'	: 27,
        'PgUp'	: 33,
        'PgDn'	: 34,
        'End'	: 35,
        'Home'	: 36,
        'Left'	: 37,
        'Up'	: 38,
        'Right'	: 39,
        'Down'	: 40,
        'Insert'	: 45,
        'Delete'	: 46,
        'F1'	: 112,
        'F2'	: 113,
        'F3'	: 114,
        'F4'	: 115,
        'F5'	: 116,
        'F6'	: 117,
        'F7'	: 118,
        'F8'	: 119,
        'F9'	: 120,
        'F10'	: 121,
        'F11'	: 122,
        'Num Lock'	: 144,
        'Scroll Lock'	: 145
};

config.shadowTiddlers.ExternalizeAsHTML = &quot;/*{{{*/\n&quot;;
config.shadowTiddlers.ExternalizeAsHTML += &quot;[Before] g\n\\n\n&lt;br/&gt;\n\n&quot;;
config.shadowTiddlers.ExternalizeAsHTML += &quot;[Before] gi\n(?:^&lt;html&gt;(.*)&lt;\/html&gt;$)|(^.*$)\n&lt;html&gt;&lt;body&gt;$1$2&lt;/body&gt;&lt;/html&gt;\n\n&quot;;
config.shadowTiddlers.ExternalizeAsHTML += &quot;[After] g\n\\n|\\t\n\n\n&quot;;
config.shadowTiddlers.ExternalizeAsHTML += &quot;[After] gi\n.*&lt;html[^&gt;]*&gt;.*&lt;body[^&gt;]*&gt;(.*)&lt;\/body&gt;&lt;\/html&gt;\n&lt;html&gt;$1&lt;/html&gt;\n\n&quot;;
config.shadowTiddlers.ExternalizeAsHTML += &quot;/*}}}*/\n&quot;;

config.shadowTiddlers.ViewTemplate = config.shadowTiddlers.ViewTemplate.replace(/\+editTiddler/,&quot;+editTiddler externalize&quot;);

config.shadowTiddlers.ExternalizeTemplate = config.shadowTiddlers.EditTemplate.replace(/macro='edit text'/,&quot;macro='externalize text'&quot;);

config.shadowTiddlers.StyleSheetExternalize = &quot;/*{{{*/\n&quot;;
config.shadowTiddlers.StyleSheetExternalize += &quot;.externalized {color: [[ColorPalette::TertiaryMid]]}\n&quot;;
config.shadowTiddlers.StyleSheetExternalize +=&quot;/*}}}*/&quot;;
store.addNotification(&quot;StyleSheetExternalize&quot;, refreshStyles);

//}}}</pre>
</div>
<div title="FCKeditor" modifier="Pascal" created="200712112146" tags="renamed" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712112146">
<pre>A great opensource Wysiwyg editor. See [[homepage|http://www.fckeditor.net/]]</pre>
</div>
<div title="FCKeditorPlugin" modifier="Pascal" created="200707031148" modified="200712211724" tags="VisualTW systemConfig Wysiwyg" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712211724" index="2">
<pre>/***
|''Name:''|FCKeditorPlugin|
|''Description:''|Wysiwyg editor for TiddlyWiki using FCKeditor.|
|''Version:''|1.1.1|
|''Date:''|Dec 21,2007|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.2.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0, others|
!Demo:
On the plugin [[homepage|http://visualtw.ouvaton.org/VisualTW.html]], see and edit [[WysiwygDemo]].
!Installation:
#download and unzip [[FCKeditor|http://www.fckeditor.net/download]] (by default, in a wiki subfolder, such that the relative path &quot;fckeditor/fckeditor.js&quot; is right).
#import [[FCKeditorPlugin]] (systemConfig tagged)
#add the following text to MarkupPreHead : {{{&lt;script type=&quot;text/javascript&quot; src=&quot;fckeditor/fckeditor.js&quot;&gt;&lt;/script&gt;}}}
#customize FCKeditorPath if needed (in MarkupPreHead and in options below)
#save and reload
#use the &lt;&lt;toolbar editHtml&gt;&gt; button in the tiddler's toolbar (in default ViewTemplate) or add {{{editHtml}}} command in your own toolbar.
! Useful Addons
*[[HTMLFormattingPlugin|http://www.tiddlytools.com/#HTMLFormattingPlugin]] to embed wiki syntax in html tiddlers.&lt;&lt;br&gt;&gt;//__Tips__ : When this plugin is installed, you can use anchor syntax to link tiddlers in wysiwyg mode (example : #example). Anchors are converted back and from wiki syntax when editing.//
*[[TaggedTemplateTweak|http://www.TiddlyTools.com/#TaggedTemplateTweak]] to use alternative ViewTemplate/EditTemplate for tiddler's tagged with specific tag values.
!Configuration options :
|FCKeditor folder (absolute or relative)|&lt;&lt;option txtFCKeditorPath&gt;&gt; |
|FCKeditor custom configuration script path (relative or absolute)&lt;&lt;br&gt;&gt;[[Example|fckeditor/editor/custom_config.js]] : {{{ fckeditor/editor/custom_config.js}}}|&lt;&lt;option txtFCKCustomConfigScript&gt;&gt;|
|Toolbar name (&quot;Default&quot;, &quot;Basic&quot; or custom)&lt;&lt;br&gt;&gt;See [[FCKeditor documentation|http://wiki.fckeditor.net/Developer%27s_Guide/Configuration/Toolbar]] for more information on custom toolbars|&lt;&lt;option txtFCKToolbar&gt;&gt;|
|FCKeditor default height (if blank = 500px)|&lt;&lt;option txtFCKheight&gt;&gt;|
|Template called by the {{{wysiwyg}}} button|EditHtmlTemplate|
!Code
***/
//{{{
config.options.txtFCKeditorPath = config.options.txtFCKeditorPath ? config.options.txtFCKeditorPath : &quot;fckeditor/&quot;;
config.options.txtFCKCustomConfigScript = config.options.txtFCKCustomConfigScript ? config.options.txtFCKCustomConfigScript : &quot;&quot;;
config.options.txtFCKToolbar = config.options.txtFCKToolbar ? config.options.txtFCKToolbar : &quot;&quot;;
config.options.txtFCKheight = config.options.txtFCKheight ? config.options.txtFCKheight : &quot;500px&quot;;

config.macros.editHtml = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		var field = params[0];
		var height = params[1] ? params[1] : config.options.txtFCKheight;
		if (typeof FCKeditor==&quot;undefined&quot;){
			displayMessage(config.macros.editHtml.FCKeditorUnavailable);
			config.macros.edit.handler(place,macroName,params,wikifier,paramString,tiddler);

		}
		else if (field) {
			var e = createTiddlyElement(null,&quot;div&quot;);
			var fckName = &quot;FCKeditor&quot;+ Math.random();
			if(tiddler.isReadOnly())
				e.setAttribute(&quot;readOnly&quot;,&quot;readOnly&quot;);
			e.setAttribute(&quot;editHtml&quot;,field);
			if (height) e.setAttribute(&quot;height&quot;,height);
			e.setAttribute(&quot;fckName&quot;,fckName);
			place.appendChild(e);
			var fck = new FCKeditor(fckName);
			fck.BasePath = config.options.txtFCKeditorPath;
			if (config.options.txtFCKCustomConfigScript) fck.Config[&quot;CustomConfigurationsPath&quot;] = config.options.txtFCKCustomConfigScript ;
			if (config.options.txtFCKToolbar) fck.ToolbarSet = config.options.txtFCKToolbar;
			fck.Height=height;
			var re = /^&lt;html&gt;(.*)&lt;\/html&gt;$/m;
			var fieldValue=store.getValue(tiddler,field);
			var htmlValue = re.exec(fieldValue);
			var value = (htmlValue &amp;&amp; (htmlValue.length&gt;0)) ? htmlValue[1] : fieldValue;
			value=value.replace(/\[\[([^|\]]*)\|([^\]]*)]]/g,'&lt;a href=&quot;#$2&quot;&gt;$1&lt;/a&gt;');
			config.macros.editHtml.FCKvalues[fckName]=value;
			e.innerHTML = fck.CreateHtml();
		}
	},
        gather : function(e) {
            var name = e.getAttribute(&quot;fckName&quot;);
            var oEditor = window.FCKeditorAPI ? FCKeditorAPI.GetInstance(name) : null;
            if (oEditor) {
                        var html = oEditor.GetHTML();
			if (html!=null) 
                                    return &quot;&lt;html&gt;&quot;+html.replace(/&lt;a href=&quot;#([^&gt;]*)&quot;&gt;([^&lt;]*)&lt;\/a&gt;/gi,&quot;[[$2|$1]]&quot;)+&quot;&lt;/html&gt;&quot;; 
            }	
        },
	FCKvalues : {},
	FCKeditorUnavailable : &quot;FCKeditor was unavailable. Check plugin configuration and reload.&quot;
}


window.FCKeditor_OnComplete= function( editorInstance ) {
        var name=editorInstance.Name;
	var value = config.macros.editHtml.FCKvalues[name];
	delete config.macros.editHtml.FCKvalues[name];
	oEditor = FCKeditorAPI.GetInstance(name);
	if (value) oEditor.SetHTML(value);
}

Story.prototype.previousGatherSaveEditHtml = Story.prototype.previousGatherSaveEditHtml ? Story.prototype.previousGatherSaveEditHtml : Story.prototype.gatherSaveFields; // to avoid looping if this line is called several times
Story.prototype.gatherSaveFields = function(e,fields){
	if(e &amp;&amp; e.getAttribute) {
		var f = e.getAttribute(&quot;editHtml&quot;);
		if(f){
			var newVal = config.macros.editHtml.gather(e);
			if (newVal) fields[f] = newVal;
		}
		this.previousGatherSaveEditHtml(e, fields);
	}
};

config.shadowTiddlers.EditHtmlTemplate = config.shadowTiddlers.EditTemplate.replace(/macro='edit text'/,&quot;macro='editHtml text'&quot;);

config.commands.editHtml={
	text: &quot;wysiwyg&quot;,
	tooltip: &quot;Edit this tiddler with a rich text editor&quot;,
	readOnlyText: &quot;&quot;,
	handler : function(event,src,title) {
		clearMessage();
		var tiddlerElem = document.getElementById(story.idPrefix + title);
		var fields = tiddlerElem.getAttribute(&quot;tiddlyFields&quot;);
		story.displayTiddler(null,title,&quot;EditHtmlTemplate&quot;,false,null,fields);
		return false;
	}
}

config.shadowTiddlers.ViewTemplate = config.shadowTiddlers.ViewTemplate.replace(/\+editTiddler/,&quot;+editTiddler editHtml&quot;);

//}}}</pre>
</div>
<div title="FieldEditorPlugin" modifier="Pascal" created="200712112158" tags="renamed" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712112158">
<pre>Renamed FieldsEditorPlugin</pre>
</div>
<div title="FieldsEditorPlugin" modifier="Pascal" created="200707031052" modified="200801041529" tags="VisualTW systemConfig Tools" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200801041529" label="FieldsEditor">
<pre>/***
|''Name:''|FieldsEditorPlugin|
|''Description:''|//create//, //edit//, //view// and //delete// commands in toolbar &lt;&lt;toolbar fields&gt;&gt;.|
|''Version:''|1.0.2|
|''Date:''|Dec 21,2007|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.2.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0, others|
!Demo:
On [[homepage|http://visualtw.ouvaton.org/VisualTW.html]], see [[FieldEditor example]]
!Installation:
*import this tiddler from [[homepage|http://visualtw.ouvaton.org/VisualTW.html]] (tagged as systemConfig)
*save and reload
*optionnaly : add the following css text in your StyleSheet : {{{#popup tr.fieldTableRow td {padding:1px 3px 1px 3px;}}}}
!Code
***/

//{{{

config.commands.fields.handlePopup = function(popup,title) {
	var tiddler = store.fetchTiddler(title);
	if(!tiddler)
		return;
	var fields = {};
	store.forEachField(tiddler,function(tiddler,fieldName,value) {fields[fieldName] = value;},true);
	var items = [];
	for(var t in fields) {
		var editCommand = &quot;&lt;&lt;untiddledCall editFieldDialog &quot;+escape(title)+&quot; &quot;+escape(t)+&quot;&gt;&gt;&quot;;
		var deleteCommand = &quot;&lt;&lt;untiddledCall deleteField &quot;+escape(title)+&quot; &quot;+escape(t)+&quot;&gt;&gt;&quot;;
		var renameCommand = &quot;&lt;&lt;untiddledCall renameField &quot;+escape(title)+&quot; &quot;+escape(t)+&quot;&gt;&gt;&quot;;
		items.push({field: t,value: fields[t], actions: editCommand+renameCommand+deleteCommand});
	}
	items.sort(function(a,b) {return a.field &lt; b.field ? -1 : (a.field == b.field ? 0 : +1);});
	var createNewCommand = &quot;&lt;&lt;untiddledCall createField &quot;+escape(title)+&quot;&gt;&gt;&quot;;
	items.push({field : &quot;&quot;, value : &quot;&quot;, actions:createNewCommand });
	if(items.length &gt; 0)
		ListView.create(popup,items,this.listViewTemplate);
	else
		createTiddlyElement(popup,&quot;div&quot;,null,null,this.emptyText);
}

config.commands.fields.listViewTemplate = {
	columns: [
		{name: 'Field', field: 'field', title: &quot;Field&quot;, type: 'String'},
		{name: 'Actions', field: 'actions', title: &quot;Actions&quot;, type: 'WikiText'},
		{name: 'Value', field: 'value', title: &quot;Value&quot;, type: 'WikiText'}
	],
	rowClasses: [
			{className: 'fieldTableRow', field: 'actions'}
	],
	buttons: [	//can't use button for selected then delete, because click on checkbox will hide the popup
	]
}

config.macros.untiddledCall = {  // when called from listview, tiddler is unset, so we need to pass tiddler as parameter
	handler : function(place,macroName,params,wikifier,paramString) {
		var macroName = params.shift();
		if (macroName) var macro = config.macros[macroName];
		var title = params.shift();
		if (title) var tiddler = store.getTiddler(unescape(title));
		if (macro) macro.handler(place,macroName,params,wikifier,paramString,tiddler);		
	}
}

config.macros.deleteField = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		if(!readOnly &amp;&amp; params[0]) {
			fieldName = unescape(params[0]);
			var btn = createTiddlyButton(place,&quot;delete&quot;, &quot;delete &quot;+fieldName,this.onClickDeleteField);
			btn.setAttribute(&quot;title&quot;,tiddler.title);
			btn.setAttribute(&quot;fieldName&quot;, fieldName);
		}
	},
	onClickDeleteField : function() {
		var title=this.getAttribute(&quot;title&quot;);
		var fieldName=this.getAttribute(&quot;fieldName&quot;);
		var tiddler = store.getTiddler(title);
		if (tiddler &amp;&amp; fieldName &amp;&amp; confirm(&quot;delete field &quot; + fieldName+&quot; from &quot; + title +&quot; tiddler ?&quot;)) {
			delete tiddler.fields[fieldName];
			store.saveTiddler(tiddler.title,tiddler.title,tiddler.text,tiddler.modifier,tiddler.modified,tiddler.tags,tiddler.fields);
			story.refreshTiddler(title,&quot;ViewTemplate&quot;,true);
		}
		return false;
	}
}

config.macros.createField = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		if(!readOnly) {
			var btn = createTiddlyButton(place,&quot;create new&quot;, &quot;create a new field&quot;,this.onClickCreateField);
			btn.setAttribute(&quot;title&quot;,tiddler.title);
		}
	},
	onClickCreateField : function() {
		var title=this.getAttribute(&quot;title&quot;);
		var tiddler = store.getTiddler(title);
		if (tiddler) {
			var fieldName = prompt(&quot;Field name&quot;,&quot;&quot;);
			if (store.getValue(tiddler,fieldName)) {
				window.alert(&quot;This field already exists.&quot;);
			}
			else if (fieldName) {
				var v = prompt(&quot;Field value&quot;,&quot;&quot;);
				tiddler.fields[fieldName]=v;
				store.saveTiddler(tiddler.title,tiddler.title,tiddler.text,tiddler.modifier,tiddler.modified,tiddler.tags,tiddler.fields);
				story.refreshTiddler(title,&quot;ViewTemplate&quot;,true);
			}
		}
		return false;
	}
}

config.macros.editFieldDialog = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		if(!readOnly &amp;&amp; params[0]) {
			fieldName = unescape(params[0]);
			var btn = createTiddlyButton(place,&quot;edit&quot;, &quot;edit this field&quot;,this.onClickEditFieldDialog);
			btn.setAttribute(&quot;title&quot;,tiddler.title);
			btn.setAttribute(&quot;fieldName&quot;, fieldName);
		}
	},
	onClickEditFieldDialog : function() {
		var title=this.getAttribute(&quot;title&quot;);
		var tiddler = store.getTiddler(title);
		var fieldName=this.getAttribute(&quot;fieldName&quot;);
		if (tiddler &amp;&amp; fieldName) {
			var value = tiddler.fields[fieldName];
			value = value ? value : &quot;&quot;;
			var lines = value.match(/\n/mg);
			lines = lines ? true : false;
			if (!lines || confirm(&quot;This field contains more than one line. Only the first line will be kept if you edit it here. Proceed ?&quot;)) {
				var v = prompt(&quot;Field value&quot;,value);
				tiddler.fields[fieldName]=v;
				store.saveTiddler(tiddler.title,tiddler.title,tiddler.text,tiddler.modifier,tiddler.modified,tiddler.tags,tiddler.fields);
				story.refreshTiddler(title,&quot;ViewTemplate&quot;,true);
			}
		}
		return false;
	}
}

config.macros.renameField = {
	handler : function(place,macroName,params,wikifier,paramString,tiddler) {
		if(!readOnly &amp;&amp; params[0]) {
			fieldName = unescape(params[0]);
			var btn = createTiddlyButton(place,&quot;rename&quot;, &quot;rename &quot;+fieldName,this.onClickRenameField);
			btn.setAttribute(&quot;title&quot;,tiddler.title);
			btn.setAttribute(&quot;fieldName&quot;, fieldName);
		}
	},
	onClickRenameField : function() {
		var title=this.getAttribute(&quot;title&quot;);
		var fieldName=this.getAttribute(&quot;fieldName&quot;);
		var tiddler = store.getTiddler(title);
		if (tiddler &amp;&amp; fieldName) {
			var newName = prompt(&quot;Rename &quot; + fieldName + &quot; as ?&quot;, fieldName);
			if (newName) {
				tiddler.fields[newName]=tiddler.fields[fieldName];
				delete tiddler.fields[fieldName];
				store.saveTiddler(tiddler.title,tiddler.title,tiddler.text,tiddler.modifier,tiddler.modified,tiddler.tags,tiddler.fields);
				story.refreshTiddler(title,&quot;ViewTemplate&quot;,true);
			}
		}
		return false;
	}
}

config.shadowTiddlers.StyleSheetFieldsEditor = &quot;/*{{{*/\n&quot;;
config.shadowTiddlers.StyleSheetFieldsEditor += &quot;.fieldTableRow td {padding : 1px 3px}\n&quot;;
config.shadowTiddlers.StyleSheetFieldsEditor += &quot;.fieldTableRow .button {border:0; padding : 0 0.2em}\n&quot;;
config.shadowTiddlers.StyleSheetFieldsEditor +=&quot;/*}}}*/&quot;;
store.addNotification(&quot;StyleSheetFieldsEditor&quot;, refreshStyles);

//}}}</pre>
</div>
<div title="Git" modifier="Jonny Gerold" created="201008102038" modified="201008102044" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201008102044">
<pre>* [[Books]]
**	[[Pro Git]]</pre>
</div>
<div title="GotoPlugin" modifier="ELSDesignStudios" created="200605052341" modified="200710312133" tags="AuthoringPackage NavigationPackage includeNew systemConfig" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200710312133">
<pre>/***
|Name|GotoPlugin|
|Source|http://www.TiddlyTools.com/#GotoPlugin|
|Version|1.4.3|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements &lt;br&gt;and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides||
|Description|view any tiddler by entering it's title - displays list of possible matches|

''View a tiddler by typing its title and pressing //enter//.''  Input just enough to uniquely match a single tiddler title and ''press //enter// to auto-complete the title for you!!''  If multiple titles match your input, a list is displayed.  You can scroll-and-click (or use arrows+enter) to select/view a tiddler, or press //escape// to close the listbox to resume typing.  When the listbox is ''//not//'' being displayed, press //escape// to clear the current text input and start over.

Note: ''At any time, you can move the focus directly to the text input field by using the ~ALT-G keyboard shortcut.''
!!!!!Examples
&lt;&lt;&lt;
| //IMPORTANT NOTE:// ''As of version 1.4.0 (2007.04.25),&lt;br&gt;to avoid conflict with javascript reserved keywords&lt;br&gt;the {{{&lt;&lt;goto&gt;&gt;}}} macro has been renamed to {{{&lt;&lt;gotoTiddler&gt;&gt;}}}'' |
syntax: {{{&lt;&lt;gotoTiddler quiet insert inputstyle liststyle&gt;&gt;}}}
All parameters are optional.
* ''quiet'' prevents //automatic// display of the list as each character is typed.  To view the list when ''quiet'', use //down// or //enter//.
* ''insert'' causes the selected tiddler title to be inserted into the tiddler source currently being edited (use with EditTemplate)
* ''inputstyle'' and ''liststyle'' are CSS declarations that modify the default input and listbox styles.  Note: styles containing spaces must be surrounded by ({{{&quot;...&quot;}}} or {{{'...'}}}) or ({{{[[...]]}}}).
{{{&lt;&lt;gotoTiddler&gt;&gt;}}}
&lt;&lt;gotoTiddler&gt;&gt;
{{{&lt;&lt;gotoTiddler quiet&gt;&gt;}}}
&lt;&lt;gotoTiddler quiet&gt;&gt;
{{{&lt;&lt;goto width:20em width:20em&gt;&gt;}}}
&lt;&lt;gotoTiddler width:20em width:20em&gt;&gt;

You can also invoke the macro with the &quot;insert&quot; keyword.  When used in the [[EditTemplate]], like this:
{{{
&lt;span macro=&quot;gotoTiddler insert&quot;&gt;&lt;/span&gt;
}}}
it allows you to type/select a tiddler title, and instantly insert a link to that title (e.g. {{{[[TiddlerName]]}}}) into the tiddler source being edited.
&lt;&lt;&lt;
!!!!!Configuration
&lt;&lt;&lt;
You can create a tiddler tagged with &lt;&lt;tag systemConfig&gt;&gt; to control the maximum height of the listbox of tiddlers/shadows/tags. //The default values are shown below://
//{{{
config.macros.gotoTiddler.listMaxSize=10;
//}}}
&lt;&lt;&lt;
!!!!!Installation
&lt;&lt;&lt;
import (or copy/paste) the following tiddlers into your document:
''GotoPlugin'' (tagged with &lt;&lt;tag systemConfig&gt;&gt;)
&lt;&lt;&lt;
!!!!!Revisions
&lt;&lt;&lt;
''2007.10.31 [1.4.3]'' removed extra trailing comma on last property of config.macros.gotoTiddler object.  This fixes an error under InternetExplorer that was introduced 6 days ago... sure, I should have found it sooner, but... ''WHY DON'T PEOPLE TELL ME WHEN THINGS ARE BROKEN!!!!''
''2007.10.25 [1.4.2]'' added onclick handler for input field, so that clicking in field hides the listbox.
''2007.10.25 [1.4.1]'' re-wrote getItems() to cache list of tiddlers/shadows/tags and use case-folded simple text match instead of regular expression to find matching tiddlers.  This *vastly* reduces processing overhead between keystrokes, especially for documents with many (&gt;1000) tiddlers.  Also, removed local definition of replaceSelection(), now supported directly by the TW2.2+ core, as well as via backward-compatible plugin (see [[CoreTweaksArchive]]).
''2007.04.25 [1.4.0]'' renamed macro from &quot;goto&quot; to &quot;gotoTiddler&quot;.  This was necessary to avoid a fatal syntax error in Opera (and other browsers) that require strict adherence to ECMAScript 1.5 standards which defines the identifier &quot;goto&quot; as &quot;reserved for FUTURE USE&quot;... *sigh*
''2007.04.21 [1.3.2]'' in html definition, removed DIV around droplist (see 1.2.6 below).  It created more layout problems then it solved. :-(
''2007.04.01 [1.3.1]'' in processItem(), ensure that correct textarea field is found by checking for edit==&quot;text&quot; attribute
''2007.03.30 [1.3.0]'' tweak SideBarOptions shadow to automatically add {{{&lt;&lt;goto&gt;&gt;}}} when using default sidebar content
''2007.03.30 [1.2.6]'' in html definition, added DIV around droplist to fix IE problem where list appears next to input field instead of below it.  
''2007.03.28 [1.2.5]'' in processItem(), set focus to text area before setting selection (needed for IE to get correct selection 'range')
''2007.03.28 [1.2.4]'' added prompt for 'pretty text' when inserting a link into tiddler content
''2007.03.28 [1.2.3]'' added local copy of core replaceSelection() and modified for different replace logic
''2007.03.27 [1.2.2]'' in processItem(), use story.getTiddlerField() to retrieve textarea control
''2007.03.26 [1.2.1]'' in html, use either 'onkeydown' (IE) or 'onkeypress' (Moz) event to process &lt;esc&gt; key sooner, to prevent &lt;esc&gt; from 'bubbling up' to the tiddler (which will close the current editor).
''2007.03.26 [1.2.0]'' added support for optional &quot;insert&quot; keyword param. When used in [[EditTemplate]], (e.g. {{{&lt;span macro=&quot;goto insert&quot;&gt;&lt;/span&gt;}}}) it triggers alternative processing: instead of displaying the selected tiddler, that tiddler's title is inserted into a tiddler's textarea edit field surrounded by {{{[[...]]}}}.
''2006.05.10 [1.1.2]'' when filling listbox, set selection to 'heading' item... auto-select first tiddler title when down/enter moves focus into listbox
''2006.05.08 [1.1.1]'' added accesskey (&quot;G&quot;) to input field html (also set when field gets focus).  Also, inputKeyHandler() skips non-printing/non-editing keys. 
''2006.05.08 [1.1.0]'' added heading to listbox for better feedback (also avoids problems with 1-line droplist)
''2006.05.07 [1.0.0]'' list matches against tiddlers/shadows/tags.  input field auto-completion... 1st enter=complete matching input (or show list)... 2nd enter=view tiddler.  optional &quot;quiet&quot; param controls when listbox appears.
''2006.05.06 [0.5.0]'' added handling for enter (13), escape(27), and down(40) keys.   Change 'ondblclick' to 'onclick' for list handler to view tiddlers (suggested by Florian Cauvin - prevents unintended trigger of tiddler editor).  shadow titles inserted into list instead of appended to the end.
''2006.05.05 [0.0.0]'' started
&lt;&lt;&lt;
!!!!!Credits
&gt;This feature was developed by EricShulman from [[ELS Design Studios|http:/www.elsdesign.com]]
!!!!!Code
***/
//{{{
version.extensions.gotoTiddler = {major: 1, minor: 4, revision: 3, date: new Date(2007,10,31)};

// automatically tweak shadow SideBarOptions to add &lt;&lt;gotoTiddler&gt;&gt; macro above &lt;&lt;search&gt;&gt;
config.shadowTiddlers.SideBarOptions=config.shadowTiddlers.SideBarOptions.replace(/&lt;&lt;search&gt;&gt;/,&quot;{{button{goto}}}\n&lt;&lt;gotoTiddler&gt;&gt;&lt;&lt;search&gt;&gt;&quot;);

config.macros.gotoTiddler= { 
	handler:
	function(place,macroName,params) {
		var quiet=(params[0] &amp;&amp; params[0]==&quot;quiet&quot;); if (quiet) params.shift();
		var insert=(params[0] &amp;&amp; params[0]==&quot;insert&quot;); if (insert) params.shift();
		var instyle=params.shift(); if (!instyle) instyle=&quot;&quot;;
		var liststyle=params.shift(); if (!liststyle) liststyle=&quot;&quot;;
		var keyevent=window.event?&quot;onkeydown&quot;:&quot;onkeypress&quot;;
		createTiddlyElement(place,&quot;span&quot;).innerHTML
			=this.html.replace(/%keyevent%/g,keyevent).replace(/%insert%/g,insert).replace(/%quiet%/g,quiet).replace(/%instyle%/g,instyle).replace(/%liststyle%/g,liststyle);
	},

	html:
	'&lt;form onsubmit=&quot;return false&quot; style=&quot;display:inline;margin:0;padding:0&quot;&gt;\
		&lt;input name=gotoTiddler type=text autocomplete=&quot;off&quot; accesskey=&quot;G&quot; style=&quot;%instyle%&quot;\
			title=&quot;enter a tiddler title&quot;\
			onclick=&quot;this.form.list.style.display=\'none\';&quot;\
			onfocus=&quot;this.select(); this.setAttribute(\'accesskey\',\'G\');&quot;\
			%keyevent%=&quot;return config.macros.gotoTiddler.inputEscKeyHandler(event,this,this.form.list);&quot;\
			onkeyup=&quot;return config.macros.gotoTiddler.inputKeyHandler(event,this,this.form.list,%quiet%,%insert%);&quot;&gt;\
		&lt;select name=list style=&quot;%liststyle%;display:none;position:absolute&quot;\
			onchange=&quot;if (!this.selectedIndex) this.selectedIndex=1;&quot;\
			onblur=&quot;this.style.display=\'none\';&quot;\
			%keyevent%=&quot;return config.macros.gotoTiddler.selectKeyHandler(event,this,this.form.gotoTiddler,%insert%);&quot;\
			onclick=&quot;return config.macros.gotoTiddler.processItem(this.value,this.form.gotoTiddler,this,%insert%);&quot;&gt;\
		&lt;/select&gt;\
	&lt;/form&gt;',

	getItems:
	function(val) {
		if (!this.items.length || val.length&lt;2) { // starting new search, refresh cached list of tiddlers/shadows/tags
			this.items=new Array();
			var tiddlers=store.getTiddlers(&quot;title&quot;,&quot;excludeLists&quot;);
			for(var t=0; t&lt;tiddlers.length; t++) this.items.push(tiddlers[t].title);
			for (var t in config.shadowTiddlers) this.items.pushUnique(t);
			var tags=store.getTags();
			for(var t=0; t&lt;tags.length; t++) this.items.pushUnique(tags[t][0]);
		}
		var found = [];
		var match=val.toLowerCase();
		for(var i=0; i&lt;this.items.length; i++)
			if (this.items[i].toLowerCase().indexOf(match)!=-1) found.push(this.items[i]);
		return found;
	},
	items: [], // cached list of tiddlers/shadows/tags

	getItemSuffix:
	function(t) {
		if (store.tiddlerExists(t)) return &quot;&quot;;  // tiddler
		if (store.isShadowTiddler(t)) return &quot; (shadow)&quot;; // shadow
		return &quot; (tag)&quot;; // tag 
	},

	keyProcessed:
	function(ev) { // utility function: exits handler and prevents browser from processing the keystroke
		ev.cancelBubble=true; // IE4+
		try{event.keyCode=0;}catch(e){}; // IE5
		if (window.event) ev.returnValue=false; // IE6
		if (ev.preventDefault) ev.preventDefault(); // moz/opera/konqueror
		if (ev.stopPropagation) ev.stopPropagation(); // all
		return false;
	},

	inputEscKeyHandler:
	function(event,here,list) {
		var key=event.keyCode;
		// escape... hide list (2nd esc=clears input)
		if (key==27) {
			if (list.style.display==&quot;none&quot;)
				here.value=here.defaultValue;
			list.style.display=&quot;none&quot;;
			return this.keyProcessed(event);
		}
		return true; // key bubbles up
	},

	inputKeyHandler:
	function(event,here,list,quiet,insert) {
		var key=event.keyCode;
		// non-printing chars... bubble up, except: backspace=8, enter=13, space=32, down=40, delete=46
		if (key&lt;48) switch(key) { case 8: case 13: case 32: case 40: case 46: break; default: return true; }
		// blank input... if down/enter... fall through (list all)... else, and hide list
		if (!here.value.length &amp;&amp; !(key==40 || key==13))
			{ list.style.display=&quot;none&quot;; return this.keyProcessed(event); }
		// find matching items...
		var found = this.getItems(here.value);
		// matched one item using enter key, but not an *exact* match... autocomplete input field
		if (found.length==1 &amp;&amp; quiet &amp;&amp; key==13 &amp;&amp; here.value!=found[0])
			{ list.style.display=&quot;none&quot;; here.value=found[0]; return this.keyProcessed(event); }
		// no match or exact match using enter key, create/show tiddler
		if (found.length&lt;2 &amp;&amp; key==13)
			return this.processItem(found.length?found[0]:here.value,here,list,insert);
		// quiet/no match, make sure list is hidden
		list.style.display=(!quiet &amp;&amp; found.length)?&quot;block&quot;:&quot;none&quot;;
		// no matches, key bubbles up
		if (!found.length) return true;
		// using down/enter key shows/moves to list...
		if (key==40 || key==13)  { list.style.display=&quot;block&quot;; list.focus(); }
		// finally, if list is showing, fill it with found results...
		if (list.style.display!=&quot;none&quot;) {
			while (list.length &gt; 0) list.options[0]=null; // clear list
			found.sort(); // alpha by title
			var hdr=found.length==1?this.listMatchMsg:this.listHeading.format([found.length]); // list 'heading'
			list.options[0]=new Option(hdr,&quot;&quot;,false,false);
			for (var t=0; t&lt;found.length; t++)  // fill list...
				list.options[list.length]=new Option(found[t]+this.getItemSuffix(found[t]),found[t],false,false);
			list.size=(found.length&lt;this.listMaxSize?found.length:this.listMaxSize)+1; // resize list...
			list.selectedIndex=(key==40 || key==13)?1:0;
		}
		return true; // key bubbles up
	},
	listMaxSize: 10,
	listHeading: 'Found %0 matching titles:',
	listMatchMsg: 'Press enter to open tiddler...',

	selectKeyHandler:
	function(event,list,editfield,insert) {
		if (event.keyCode==27) // escape... hide list, move to edit field
			{ editfield.focus(); list.style.display=&quot;none&quot;; return this.keyProcessed(event); }
		if (event.keyCode==13 &amp;&amp; list.value.length) // enter... view selected item
			{ this.processItem(list.value,editfield,list,insert); return this.keyProcessed(event); }
		return true; // key bubbles up
	},

	processItem:
	function(title,here,list,insert) {
		if (!title.length) return; here.value=title; list.style.display='none';
		if (insert) {
			var tidElem=story.findContainingTiddler(here); if (!tidElem) { here.focus(); return false; }
			var e=story.getTiddlerField(tidElem.getAttribute(&quot;tiddler&quot;),&quot;text&quot;);
			if (!e||e.getAttribute(&quot;edit&quot;)!=&quot;text&quot;) return false;
			var txt=prompt(this.askForText,title); if (!txt||!txt.length) { here.focus(); return false; }
			e.focus(); // put focus on target field before setting selection
			replaceSelection(e,&quot;[[&quot;+txt+&quot;|&quot;+title+&quot;]]&quot;); // insert selected tiddler as a PrettyLink
		}
		else
			story.displayTiddler(null,title); // show selected tiddler
		return false;
	},
	askForText: &quot;Enter the text to display for this link&quot;
}
//}}}</pre>
</div>
<div title="HTMLFormattingPlugin" modifier="ELSDesignStudios" created="200512011522" modified="200712042054" tags="FormattingPackage MediaPackage includeNew systemConfig" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712042054">
<pre>/***
|Name|HTMLFormattingPlugin|
|Source|http://www.TiddlyTools.com/#HTMLFormattingPlugin|
|Version|2.1.5|
|Author|Eric Shulman - ELS Design Studios|
|License|http://www.TiddlyTools.com/#LegalStatements &lt;br&gt;and [[Creative Commons Attribution-ShareAlike 2.5 License|http://creativecommons.org/licenses/by-sa/2.5/]]|
|~CoreVersion|2.1|
|Type|plugin|
|Requires||
|Overrides|'HTML' formatter|
|Description|embed wiki syntax formatting inside of HTML content|

The shorthand Wiki-style formatting syntax of ~TiddlyWiki is very convenient and enables most content to be reasonably well presented. However, there are times when tried-and-true HTML formatting syntax allows more more precise control of the content display.

When HTML formatting syntax is embedded within a tiddler (in between {{{&lt;}}}{{{html&gt;}}} and {{{&lt;}}}{{{/html&gt;}}} markers) TiddlyWiki passes this content to the browser for processing as 'native' HTML.  However, TiddlyWiki does not also process the HTML source content for any embedded wiki-formatting syntax it may contain.  This means that while you can use HTML formatted content, you cannot mix wiki-formatted content within the HTML formatting.
!!!!!Usage
&lt;&lt;&lt;
The ~HTMLFormatting plugin allows you to freely ''mix wiki-style formatting syntax within HTML formatted content'' by extending the action of the standard TiddlyWiki formatting handler.

When a tiddler is about to be displayed, ~TiddlyWiki looks for tiddler content contained within ''&lt;{{{html}}}&gt;'' and ''&lt;{{{/html}}}&gt;'' HTML tags.  This content (if any) is passed directly to the browser's internal &quot;rendering engine&quot; to process as ~HTML-formatted content.  Once the HTML formatting has been processed, all the pieces of text occuring in between the HTML formatting are then processed by the ~TiddlyWiki rendering engine, one piece at a time, so that normal wiki-style formatting can be applied to the individual text pieces.
&lt;&lt;&lt;
!!!!!Line breaks
&lt;&lt;&lt;
One major difference between Wiki formatting and HTML formatting is how &quot;line breaks&quot; are processed. Wiki formatting treats all line breaks as literal content to be displayed //as-is//. However, because HTML normally ignores line breaks and actually processes them as simple &quot;word separators&quot; instead, many people who write HTML include extra line breaks in their documents, just to make the &quot;source code&quot; easier to read.

Even though you can use HTML tags within your tiddler content, the default treatment for line breaks still follows the Wiki-style rule (i.e., all new lines are displayed as-is). When adding HTML content to a tiddler (especially if you cut-and-paste it from another web page), you should take care to avoid adding extra line breaks to the text.

If removing all the extra line breaks from your HTML content would be a big hassle, you can quickly //override the default Wiki-style line break rule// so that the line breaks use the standard HTML rules instead.  Placing a ''&lt;{{{hide linebreaks}}}&gt;'' tag within the tiddler's HTML content changes all line breaks to spaces before rendering the content, so that the literal line breaks will be processed as simple word-breaks instead.

Note: this does //not// alter the actual tiddler content that is stored in the document, just the manner in which it is displayed. Any line breaks contained in the tiddler will still be there when you edit its content. Also, to include a literal line break when the ''&lt;{{{hide linebreaks}}}&gt;'' tag is present, you will need to use a ''&lt;{{{br}}}&gt;'' or ''&lt;{{{p}}}&gt;'' HTML tag instead of simply typing a line break.
&lt;&lt;&lt;
!!!!!How it works
&lt;&lt;&lt;
The TW core support for HTML does not let you put ANY wiki-style syntax (including TW macros) *inside* the {{{&lt;html&gt;...&lt;/html&gt;}}} block.  Everything between {{{&lt;html&gt;}}} and {{{&lt;/html&gt;}}} is handed to the browser for processing and that is it.  Fortunately, this plugin ADDS the ability to let you put wiki-syntax (including macros) inside the html.  It does this by first giving the tiddler source content to the browser to process the HTML, and then handling any wiki-based syntax that remains afterward.

However, not all wiki syntax can be safely passed through the browser's parser. Specifically, any TW macros inside the HTML will get 'eaten' by the browser since the macro brackets, {{{&lt;&lt;...&gt;&gt;}}} use the &quot;&lt;&quot; and &quot;&gt;&quot; that normally delimit the HTML/XML syntax recognized by the browser's parser.

Similarly, you can't use InlineJavascript within the HTML because the {{{&lt;script&gt;...&lt;/script&gt;}}} syntax will also be consumed by the browser and there will be nothing left to process afterward.  Note: unfortunately, even though the browser removes the {{{&lt;script&gt;...&lt;/script&gt;}}} sequence, it doesn't actually execute the embedded javascript code that it removes, so any scripts contained inside of &lt;html&gt; blocks in TW are currently being ignored. :-(

As a work-around to allow TW *macros* (but not inline scripts) to exist inside of &lt;html&gt; formatted blocks of content, the plugin first converts the {{{&lt;&lt;}}} and {{{&gt;&gt;}}} into &quot;%%(&quot; and &quot;)%%&quot;, making them &quot;indigestible&quot; so they can pass unchanged through the belly of the beast (the browser's HTML parser).

After the browser has done its job, the wiki syntax sequences (including the &quot;undigested&quot; macros) are contained in #text nodes in the browser-generated DOM elements.  The plugin then recursively locates and processes each #text node, converts the %%( and )%% back into {{{&lt;&lt;}}} and {{{&gt;&gt;}}}, passes the result to wikify() for further rendering of the wiki-formatted syntax into a containing SPAN that replaces the previous #text node.  At the end of this process, none of the encoded %%( and )%% sequences remain in the rendered tiddler output.
&lt;&lt;&lt;
!!!!!Installation
&lt;&lt;&lt;
import (or copy/paste) the following tiddlers into your document:
''HTMLFormattingPlugin'' (tagged with &lt;&lt;tag systemConfig&gt;&gt;)
^^documentation and javascript for HTMLFormatting handling^^
&lt;&lt;&lt;
!!!!!Revision History
&lt;&lt;&lt;
''2007.12.04 [*.*.*]'' update for TW2.3.0: replaced deprecated core functions, regexps, and macros
''2007.06.14 [2.1.5]'' in formatter, removed call to e.normalize().  Creates an INFINITE RECURSION error in Safari!!!!
''2006.09.10 [2.1.4]'' update formatter for 2.1 compatibility (use this.lookaheadRegExp instead of temp variable)
''2006.05.28 [2.1.3]'' in wikifyTextNodes(), decode the *value* of TEXTAREA nodes, but don't wikify() its children.  (thanks to &quot;ayj&quot; for bug report)
''2006.02.19 [2.1.2]'' in wikifyTextNodes(), put SPAN element into tiddler DOM (replacing text node), BEFORE wikifying the text content.  This ensures that the 'place' passed to any macros is correctly defined when the macro is evaluated, so that calls to story.findContainingTiddler(place) will work as expected. (Thanks for bug report from GeoffSlocock)
''2006.02.05 [2.1.1]'' wrapped wikifier hijack in init function to eliminate globals and avoid FireFox 1.5.0.1 crash bug when referencing globals
''2005.12.01 [2.1.0]'' don't wikify #TEXT nodes inside SELECT and TEXTAREA elements
''2005.11.06 [2.0.1]'' code cleanup
''2005.10.31 [2.0.0]'' replaced hijack wikify() with hijack config.formatters[&quot;html&quot;] and simplified recursive WikifyTextNodes() code
''2005.10.09 [1.0.2]'' combined documentation and code into a single tiddler
''2005.08.05 [1.0.1]'' moved HTML and CSS definitions into plugin code instead of using separate tiddlers
''2005.07.26 [1.0.1]'' Re-released as a plugin. Added &lt;{{{html}}}&gt;...&lt;/{{{nohtml}}}&gt; and &lt;{{{hide newlines}}}&gt; handling
''2005.07.20 [1.0.0]'' Initial Release (as code adaptation)
&lt;&lt;&lt;
!!!!!Credits
&lt;&lt;&lt;
This feature was developed by EricShulman from [[ELS Design Studios|http:/www.elsdesign.com]]
&lt;&lt;&lt;
!!!!!Code
***/
//{{{
version.extensions.HTMLFormatting = {major: 2, minor: 1, revision: 5, date: new Date(2007,6,14)};

// find the formatter for HTML and replace the handler
initHTMLFormatter();
function initHTMLFormatter()
{
	for (var i=0; i&lt;config.formatters.length &amp;&amp; config.formatters[i].name!=&quot;html&quot;; i++);
	if (i&lt;config.formatters.length)	config.formatters[i].handler=function(w) {
		if (!this.lookaheadRegExp)  // fixup for TW2.0.x
			this.lookaheadRegExp = new RegExp(this.lookahead,&quot;mg&quot;);
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source)
		if(lookaheadMatch &amp;&amp; lookaheadMatch.index == w.matchStart) {
			var html=lookaheadMatch[1];
			// optionally suppress wiki-style literal handling of newlines
			// strip any carriage returns added by Internet Explorer's textarea edit field
			// encode newlines as \n so Internet Explorer's HTML parser won't eat them
			// encode macro brackets (&lt;&lt; and &gt;&gt;) so HTML parser won't eat them
			if (html.indexOf('&lt;hide linebreaks&gt;')!=-1) html=html.replace(/\n/g,' ');
			html=html.replace(/\r/g,'');
			html=html.replace(/\n/g,'\\n');
			html=html.replace(/&lt;&lt;/g,'%%(').replace(/&gt;&gt;/g,')%%');
			// create span to hold HTML
			// parse HTML and normalize the results
			// walk node tree and call wikify() on each text node
			var e = createTiddlyElement(w.output,&quot;span&quot;);
			e.innerHTML=html;
			// REMOVED: e.normalize();  // THIS CAUSED INFINITE RECURSION IN SAFARI
			wikifyTextNodes(e);
			// advance to next parse position
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
}

// wikify text nodes remaining after HTML content is processed (pre-order recursion)
function wikifyTextNodes(theNode)
{
	// textarea node doesn't get wikified, just decoded... 
	if (theNode.nodeName.toLowerCase()=='textarea')
		theNode.value=theNode.value.replace(/\%%\(/g,'&lt;&lt;').replace(/\)\%%/g,'&gt;&gt;').replace(/\\n/g,'\n');
	else for (var i=0;i&lt;theNode.childNodes.length;i++) {
		var theChild=theNode.childNodes.item(i);
		if (theChild.nodeName.toLowerCase()=='option') continue;
		if (theChild.nodeName.toLowerCase()=='select') continue;
		wikifyTextNodes(theChild);
		if (theChild.nodeName=='#text') {
			var txt=theChild.nodeValue;
			// decode macro brackets and newlines
			txt=txt.replace(/\%%\(/g,'&lt;&lt;').replace(/\)\%%/g,'&gt;&gt;').replace(/\\n/g,'\n');
			// replace text node with wikified() span
			var newNode=createTiddlyElement(null,&quot;span&quot;);
			theNode.replaceChild(newNode,theChild);
			wikify(txt,newNode);
		}
	}
}
//}}}</pre>
</div>
<div title="HideWhenPlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|HideWhenPlugin|
|Description:|Allows conditional inclusion/exclusion in templates|
|Version:|3.1 ($Rev: 3919 $)|
|Date:|$Date: 2008-03-13 02:03:12 +1000 (Thu, 13 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#HideWhenPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
For use in ViewTemplate and EditTemplate. Example usage:
{{{&lt;div macro=&quot;showWhenTagged Task&quot;&gt;[[TaskToolbar]]&lt;/div&gt;}}}
{{{&lt;div macro=&quot;showWhen tiddler.modifier == 'BartSimpson'&quot;&gt;&lt;img src=&quot;bart.gif&quot;/&gt;&lt;/div&gt;}}}
***/
//{{{

window.hideWhenLastTest = false;

window.removeElementWhen = function(test,place) {
	window.hideWhenLastTest = test;
	if (test) {
		removeChildren(place);
		place.parentNode.removeChild(place);
	}
};


merge(config.macros,{

	hideWhen: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( eval(paramString), place);
	}},

	showWhen: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !eval(paramString), place);
	}},

	hideWhenTagged: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.tags.containsAll(params), place);
	}},

	showWhenTagged: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !tiddler.tags.containsAll(params), place);
	}},

	hideWhenTaggedAny: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.tags.containsAny(params), place);
	}},

	showWhenTaggedAny: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !tiddler.tags.containsAny(params), place);
	}},

	hideWhenTaggedAll: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.tags.containsAll(params), place);
	}},

	showWhenTaggedAll: { handler: function (place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !tiddler.tags.containsAll(params), place);
	}},

	hideWhenExists: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( store.tiddlerExists(params[0]) || store.isShadowTiddler(params[0]), place);
	}},

	showWhenExists: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !(store.tiddlerExists(params[0]) || store.isShadowTiddler(params[0])), place);
	}},

	hideWhenTitleIs: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.title == params[0], place);
	}},

	showWhenTitleIs: { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( tiddler.title != params[0], place);
	}},

	'else': { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		removeElementWhen( !window.hideWhenLastTest, place);
	}}

});

//}}}

</pre>
</div>
<div title="InstantTimestampPlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|InstantTimestampPlugin|
|Description:|A handy way to insert timestamps in your tiddler content|
|Version:|1.0.10 ($Rev: 3646 $)|
|Date:|$Date: 2008-02-27 02:34:38 +1000 (Wed, 27 Feb 2008) $|
|Source:|http://mptw.tiddlyspot.com/#InstantTimestampPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Usage
If you enter {ts} in your tiddler content (without the spaces) it will be replaced with a timestamp when you save the tiddler. Full list of formats:
* {ts} or {t} -&gt; timestamp
* {ds} or {d} -&gt; datestamp
* !ts or !t at start of line -&gt; !!timestamp
* !ds or !d at start of line -&gt; !!datestamp
(I added the extra ! since that's how I like it. Remove it from translations below if required)
!!Notes
* Change the timeFormat and dateFormat below to suit your preference.
* See also http://mptw2.tiddlyspot.com/#AutoCorrectPlugin
* You could invent other translations and add them to the translations array below.
***/
//{{{

config.InstantTimestamp = {

	// adjust to suit
	timeFormat: 'DD/0MM/YY 0hh:0mm',
	dateFormat: 'DD/0MM/YY',

	translations: [
		[/^!ts?$/img,  &quot;'!!{{ts{'+now.formatString(config.InstantTimestamp.timeFormat)+'}}}'&quot;],
		[/^!ds?$/img,  &quot;'!!{{ds{'+now.formatString(config.InstantTimestamp.dateFormat)+'}}}'&quot;],

		// thanks Adapted Cat
		[/\{ts?\}(?!\}\})/ig,&quot;'{{ts{'+now.formatString(config.InstantTimestamp.timeFormat)+'}}}'&quot;],
		[/\{ds?\}(?!\}\})/ig,&quot;'{{ds{'+now.formatString(config.InstantTimestamp.dateFormat)+'}}}'&quot;]
		
	],

	excludeTags: [
		&quot;noAutoCorrect&quot;,
		&quot;noTimestamp&quot;,
		&quot;html&quot;,
		&quot;CSS&quot;,
		&quot;css&quot;,
		&quot;systemConfig&quot;,
		&quot;systemConfigDisabled&quot;,
		&quot;zsystemConfig&quot;,
		&quot;Plugins&quot;,
		&quot;Plugin&quot;,
		&quot;plugins&quot;,
		&quot;plugin&quot;,
		&quot;javascript&quot;,
		&quot;code&quot;,
		&quot;systemTheme&quot;,
		&quot;systemPalette&quot;
	],

	excludeTiddlers: [
		&quot;StyleSheet&quot;,
		&quot;StyleSheetLayout&quot;,
		&quot;StyleSheetColors&quot;,
		&quot;StyleSheetPrint&quot;
		// more?
	]

}; 

TiddlyWiki.prototype.saveTiddler_mptw_instanttimestamp = TiddlyWiki.prototype.saveTiddler;
TiddlyWiki.prototype.saveTiddler = function(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created) {

	tags = tags ? tags : []; // just in case tags is null
	tags = (typeof(tags) == &quot;string&quot;) ? tags.readBracketedList() : tags;
	var conf = config.InstantTimestamp;

	if ( !tags.containsAny(conf.excludeTags) &amp;&amp; !conf.excludeTiddlers.contains(newTitle) ) {

		var now = new Date();
		var trans = conf.translations;
		for (var i=0;i&lt;trans.length;i++) {
			newBody = newBody.replace(trans[i][0], eval(trans[i][1]));
		}
	}

	// TODO: use apply() instead of naming all args?
	return this.saveTiddler_mptw_instanttimestamp(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created);
}

// you can override these in StyleSheet 
setStylesheet(&quot;.ts,.ds { font-style:italic; }&quot;,&quot;instantTimestampStyles&quot;);

//}}}

</pre>
</div>
<div title="JavaGlue.00 Agenda" modifier="StephenWilliams" created="201103080808" modified="201103100020" tags="AnDevCon2011 JavaGlue" changecount="30">
<pre># About [[JavaGlue.01 About]]
This presentation can be found at: http://sdw.st/javaglue.html#tag:JavaGlue
## Introduction
# Improvements [[JavaGlue.02 Improvements]]
# A [[JavaGlue.03 JNI Primer]]: Java with C and C++
## Calling C methods
## Passing Data
### Scalars
### Strings
### Byte arrays
## JNI References
### Local References
### Global References
## C to Java
### Allocating scalar arrays
### Allocating strings
### Calling Java methods
# [[JavaGlue.04 Alternatives]]
## Hand-coded JNI
### [[JavaGlue.04.1 JNI Diagrams]]
## SWIG
## JNA
# [[JavaGlue.05 Use]]
## Capabilities
## Limitations
## A Simple JavaGlue Example: [[JavaGlue.05.1 Example 1]]
## [[JavaGlue.05.2 JavaGlue Diagrams]]
## [[JavaGlue.07 Memory Management]]
## [[JavaGlue.08 Utility Methods]]
## [[JavaGlue.06 JavaGlue Build System]]
# How does JavaGlue work? [[JavaGlue.10 Internals]]
# [[JavaGlue.11 Adanced JNI]]
### Long-lived C references to Java objects
### SuperGlue: Java Subclass of a C++ Class Used as a Plugin to a plain C++ Object
# [[JavaGlue.12 CMake]]
## Main Characteristics
## Simple Examples
## Building with NDK
## Building JavaGlue Projects
## Integrating with Java / Android / Eclipse
# Planned Improvements
# [[About Us|OptimaLogic]]

</pre>
</div>
<div title="JavaGlue.01 About" modifier="StephenWilliams" created="201103080644" modified="201104022055" tags="JavaGlue AnDevCon2011" changecount="29">
<pre>!About
Authors: Stephen Williams (sdw@lig.net), with help from Kevin Campbell (kcsasquatch@yahoo.com) and excerpts from the Ogre4j project page (link 1 below).

JavaGlue is a development tool that takes C/C++ headers as input and produces C/C++ and Java glue code that allows nearly all C++ constructs to be used directly by Java code.  Once integrated into a build environment, almost no work is needed to write Java code that allocates and manipulates C++ code easily.
!!Introduction
JavaGlue is a fork of XBiG.  Why: 
# Avoid breaking current usage of XBiG, 
# Avoid worrying about breaking things, 
# While getting out new features, 
# An easier to use build system, and most importantly,
# Using a more memorable (and easier to Google) name.  
!!! XBiG &amp; NoodleGlue
The XSLT Bindings Generator - XBiG - is a project that uses XSL transformations to generate foreign function interfaces (bindings) for libraries (http://code.google.com/p/xbig/).  XBiG was derived from an older project called NoodleGlue (http://web.archive.org/web/20070205204525rn_1/www.noodleglue.org/noodleglue/noodleglue.html, http://www.stuartaxon.com/2008/10/01/noodleglue-found/). 

Specifically, XBiG is designed to generate Java code and JNI bindings that allow almost any native (i.e. C or C++) library to be used from Java.  XBig was initially used to create Java OGRE (http://www.ogre3d.org/) bindings as the Ogre4j project (http://ogre4j.sourceforge.net/).

JavaGlue changes are minor compared to the work that obviously went into creating NoodleGlue and XBiG.  It is assumed that JavaGlue and XBiG will merge eventually.
!!Licensing
The code generation tool is GPL.  The linkable libraries from XBiG are LGPL.  JavaGlue additions are Apache 2.0 where this doesn't conflict with XBiG licensing.  Generated code, as is generally the case with code generators and compilers, is owned by the owner of the input.
!!Download
Google Code shortly.  Snag it here for now: http://sdw.st/conf/AnDevCon2011/javaglue-1.0.zip
!!The Name
Our hope is that the name JavaGlue will be as discoverable, descriptive and generic as the tool itself should be.  It is likely that XBiG and JavaGlue will merge.  May the most useful name win.
!!Kudos for Past &amp; Current Work By
* NoodleHeaven / Noodleglue.org (Tool released as GPL, with generated code and runtime code having no restrictions (i.e. public domain / user owned).)
* NetAllied (Believed to be current owners of XBiG copyright, tool GPL, runtime code LGPL.  MIT or Apache requested.)
** Christoph Nenning
** Sebastian@opencollada.org
!!!Related Links
# http://sourceforge.net/apps/mediawiki/ogre4j/index.php?title=White_Paper
# http://ogre4j.sourceforge.net/
!!!!Projects with similar goals
* http://www.itk.org/ITK/resources/CableSwig.html
* http://jsegue.sourceforge.net/
* http://sourceforge.net/projects/jsegue/

</pre>
</div>
<div title="JavaGlue.02 Improvements" modifier="StephenWilliams" created="201103080609" modified="201103090900" tags="AnDevCon2011 JavaGlue" changecount="16">
<pre>!Improvements of XBiG
We have enhanced XBiG significantly to meet our needs, adding the following functionality:
* Support for passing null pointers as arguments to and from C/C++ functions
* Efficient and easy byte array movement between Java &amp; C++
* Better handling of input include file hierarchies
* Improved build system
* A number of bugs fixed
* Finding and working around details for using with Android
!!Design Goals
* Minimize or eliminate the need for the native code to be &quot;JavaGlue-aware&quot;.  Ideally, an existing native library could be wrapped naturally in Java without requiring any changes to the native code.  In practice this may not completely be the case, but the required changes are fairly small and non-invasive.
* Support &quot;callback interfaces&quot;, where native code calls back to methods on objects implemented in Java
* Ensure that applications which use code generated by JavaGlue are not bound by licensing restrictions</pre>
</div>
<div title="JavaGlue.03 JNI Primer" modifier="StephenWilliams" created="201103090108" modified="201103090900" tags="AnDevCon2011 JavaGlue" changecount="12">
<pre>[[JNI Diagrams]]
# Calling C methods
# Passing Data
## Scalars
## Strings
## Byte arrays
# JNI References
## Local References
## Global References
# C to Java
## Allocating scalar arrays
## Allocating strings
## Calling Java methods
</pre>
</div>
<div title="JavaGlue.04 Alternatives" modifier="StephenWilliams" created="201103080928" modified="201103090902" tags="AnDevCon2011 JavaGlue" changecount="11">
<pre>!JavaGlue Alternatives
JavaGlue alternatives either involve writing and maintaining a lot of metadata, fragile and verbose hand coding, or libraries that have a lot of run time inefficiencies.  No other freely available library is available that uses only C++ header files as input and generates all Java and C/C++ glue code needed to immediately write Java code that can pretty much universally use C++ objects.
!! Hand-coded JNI
Hand-coded JNI is time consuming, verbose, not typesafe at all, error prone, and hard to maintain.  And it only directly supports Java-&gt;C and C-&gt;Java calls.  Handling C++ code requires you to create functions with unmangled C linkage that would need to take pointers as integer parameters, to cast properly, and then to make the C++ method calls desired.  All scalar types need to be mapped in each direction with JNI methods to be called to convert strings, etc.  Additionally, the linkage both ways is interpreted at runtime so typos and out of date interfaces are not detected until a method call is attempted.  How many people have full code coverage built into their projects?

For a few C methods, or very limited linkage to C++, this is doable.  There are several steps, but it isn't too difficult.  However, none of the code involved does anything useful and debugging can be timeconsuming.
* http://download.oracle.com/javase/1.5.0/docs/guide/jni/
* http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/jniTOC.html
* http://java.sun.com/docs/books/jni/
* http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html
!! Simplified Wrapper and Interface Generator (SWIG)
SWIG is a nice system that allows wrapping C/C++ code for Java, many scripting languages, and other targets.  It is flexible and tunable in many ways.  However, it does usually take some manual configuration file creation.  Also, some choices are probably not as desirable as JavaGlue solutions, like the way that pass by value and &quot;char *&quot; situations are handled.  The typed pointers as strings is interesting, but it will be much slower than the direct passing of pointers in JavaGlue.
* http://www.swig.org/
!! Java Native Access (JNA)
JNA is a Java library that includes a native code module that can be used to interpretively map access to native methods, structures, and variables.  It is said to be about 1/10th the speed of similar JNI calls.  It also has some limitations, would take work to port to Android since it uses an ugly native access method, and is not very popular.
* http://jna.java.net/
!! Rationale from the XBiG Authors:
__From: http://sourceforge.net/apps/mediawiki/ogre4j/index.php?title=White_Paper__
&lt;&lt;&lt;
One big point for every project that implements wrapper(s) for a library in different programming languages is the effort to maintain the wrapper code. The target library has their own release cycles and most major releases introduce API breaking changes. Most of the projects deal with this issue by using code generators which create the necessary bindings automatically. We evaluated the application of several code generators such as SWIG (Simplified Wrapper and Interface Generator) and NoddleGlue but none of the tested tools met our requirements. SWIG needs very much effort beforehand because every interface that should be wrapped needs a interface description file. Both tools miss full support of C/C++ templates which are used quite often in OGRE. For this and other reasons we decided in autumn 2005 to implement our own generator based on the same technologies as NoodleGlue. Since autumn 2006 the JNI code generator project is forked from ogre4j under the name XBiG (XSLT Bindings Generator) and got its own project space on Sourceforge.net.

NoodleGlue is the wrapper generation tool of &quot;noodle heaven&quot; and uses doxygen to extract the API information from the library's source code. This approach had the advantage that parsing and analyzing is done by a tool that is widely-used and tested with different input languages. So the first step to our generator was already available for free. Besides the usual outputs like a HTML documentation Doxygen provides a XML output of the analysed source code. This output is specialized for the Doxygen task to generate documentation, contains a lot of information that isn't necessary to generate wrapper code and is structured in a flat (E.g. name spaces are not nested as child XML elements.) hierarchy. For these reasons and to have the possibility to replace Doxygen with another tool, we decided to implement a meta layer that is represented in XML too.

To convert the Doxygen output to our meta layer we're using XSLT (Extensible Stylesheet Language Transformations) which is designed to describe conversions or transformations of XML code with XML code. One big advantage of XSLT is that it is an interpreted language and therefore OS (Operation System) independent. The generation of the meta layer and the layer itself should be independent from any OS or platform to make it possible to generate bindings for &quot;every&quot; language on every platform. To have a consistent tool chain the generation of the wrapper code is done with XSLT too. This reduces the usage of different tools and technologies to one major aspect: XML/XSLT. As mentioned before, Doxygen could be replaced with another tool that is capable of parsing source code and generating a XML representation of the parsed input.
&lt;&lt;&lt;</pre>
</div>
<div title="JavaGlue.04.1 JNI Diagrams" modifier="StephenWilliams" created="201103090117" modified="201103091855" tags="AnDevCon2011 JavaGlue [[JavaGlue.03 JNI Primer]]" changecount="14">
<pre>!Standard JNI / NDK Development Process
(Images courtesy of Marko Gargenta of Marakana.)
[&lt;img[Used with permission of Marko Gargenta of marakana.com|BuildingAndRunningJNICodeMini.png]]
[img[Used with permission of Marko Gargenta of marakana.com|UsingNDKMini.png]]</pre>
</div>
<div title="JavaGlue.05 Use" modifier="StephenWilliams" created="201103081126" modified="201103090951" tags="AnDevCon2011 JavaGlue" changecount="9">
<pre>!Capabilities
JavaGlue provides access to just about everything in C/C++ that you would reasonably want access to from Java.  Setters and getters are created for access to public data.  Public constructors, destructors, methods, and types are all available.  Globals, class static, and object members are available in a fairly clean way.  Both factory methods and Java-side 'new' of objects is supported, along with pass and return by value.  Enums, template types (possibly requiring typedef), std:string, Vector&lt;byte&gt;, and unsigned char*[] are all supported.  Direct support for handling pointers, including null pointers, and passing by reference, are all handled in a straightforward and very C++-like way.  Name spaces and class hierarchies are handled by direct mapping to Java package name space.  Even C++ multiple inheritance is mapped to Java in a usable way.  Type mapping can be tuned as needed.  C++ items in headers can be ignored with a couple levels of granularity through a config file.

The net result is that through no creation of metadata or programming, you can point the build system at a hierarchical directory of C and C++ headers, build, and write very C++-like Java code that directly uses C++ code.  And because the C++ code has been mirrored into generated Java code, Eclipse will provide tooltip assistance while writing C++-ish Java code.
# Global methods &amp; members - These show up as static methods in a class called GlobalUtility which is created as necessary at every package level.
# Variables - Public variables get getters and setters automatically created.
# Classes - Public classes are fully wrapped and proxied into Java classes, usually with a Java class with the same name and an interface with 'I' prepended. 
# Methods - All public methods are available.  Those returning objects by value have a slightly modified form in Java: They return void and have an extra first parameter which must be an already constructed object.
# Constructors &amp; Destructors - These are proxied normally into Java.
# Template instances - These are supported, however parameterized templates often must be typedef'd to be usable.  Methods with an untypedefed complex template type as a paramter or return value will simply be ignored and won't exist in Java.
# Typedefs - C++ treats typedefs as equivalent to the original type, while JavaGlue wraps them into Java classes and interfaces of the same name.
# Enums - Completely usable, including created mapping methods.  Java use of C++ enum values looks different than C++ use of enum, but the semantics are mapped well.
!Limitations
# Templates have to have a concrete instance
# Parameterized templates often need to be typedef'd.  Since types in any form are equivalent in C++, this is easy.
# Template or other code instantiation must obviously be triggered in C++.  When writing code in Java, it is too late.  In many cases JavaGlue will generate code that will make it happen.  Making use of something in Java is often just a matter of adding a typedef.
# JavaGlue will sometimes create code to access members or base classes that are not public, causing compilation errors in the generated C++ code.  This can be avoided by adding ignore statements to ignore_list.xml or hiding code from the JavaGlue analysis.
!Temporary Limitations
# No '_' in enum type names.  (Name mangling requires that '_' -&gt; '_1'.  This happens elsewhere and needs to be fixed for enum types.)
# The generated C++ code may have trouble finding include files in some cases.  Paths weren't preserved in the Doxygen output.  JavaGlue is improved here as it tries to regenerate the original paths, but the method isn't foolproof.
# Can't change the name of shared libraries or generated paths.  They are xbig and org.xbig currently.  Will change to org.javaglue, and be modifiable soon.
# The original XBiG library code must end up in a separate shared library from generated application code so that the LGPL relink requirement can be met easily.  This will be fixed shortly.  Please consider the current code development only until then.
# C++ wstring handling code is currently missing due to now-obsolete Android STL issues.  Wstring support will return soon.</pre>
</div>
<div title="JavaGlue.05.1 Example 1" modifier="StephenWilliams" created="201103090844" modified="201103090957" tags="AnDevCon2011 JavaGlue Example" changecount="5">
<pre>//Better examples pending.//

test.h:
&lt;code C++&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;string&gt;
#include &lt;vector&gt;
#include &lt;jni.h&gt;
#include &quot;basedelete.h&quot;
#include &quot;jni_base.h&quot;

// typedef std::vector&lt;unsigned char&gt; ByteVector; Get this from modified Xbig now.
class test {
 public:
  int x;
  float y;
  char *p;
  test() { p = NULL; }
  test(char *pp) { p = pp; }
  bool isNullFlag;
  char * doWhatever(char *pp) { if (pp == NULL) isNullFlag = true; else isNullFlag = false; return pp; }
  std::string * mkStringP(std::string s) { return new std::string(s); }
  void setString(std::string s) { p = strdup(s.c_str()); }
  void setStringP(std::string *s) { p = strdup(s-&gt;c_str()); delete s; }
  std::string getString() { return std::string(p); }
  char *getCString() { return p; }
  char *dupcString(std::string s) { return strdup(s.c_str()); }
  bool isNull() { return isNullFlag; }
  bool isTestNull(test *tt) {
    if (tt == NULL) isNullFlag = true; else isNullFlag = false; return isNullFlag;
  }
  bool isTest(test tt) {
    // if (tt == NULL) isNullFlag = true; else isNullFlag = false; return isNullFlag;
  }
  test* getTest() { return this; }
  test* getTestNull() { return (test*)NULL; }
  static base::ByteVector&amp; mkByteVector() {
    base::ByteVector* bp = new base::ByteVector(20);
    (*bp)[0] = 'h'; (*bp)[1] = 'i';
    return *bp;
  }

  // std::wstring ws;
  // std::wstring getWString() { return ws; }

  static void bvDouble(base::ByteVector, base::ByteVector) {
    
  }

};

class test2 {
   public:
   test t;
   int i;
   test2() {
   }
   test2(int ip) {
     i=ip;
   }
};

class test3 {
  int j;
  void* p3;
 public:
  test3() { p3 = 0; }
  void* getP3() { return p3; }
};

class test4: public test, public test3 {
 public:
  test4() { }
};
&lt;/code&gt;
BasicTests.java:
&lt;code Java&gt;
/**
 * 
 */
package test;
import org.xbig.base.*;
import org.xbig.std.*;

import org.xbig.*;

// import org.junit.Assert;
// import org.junit.Test;
// import junit.framework.TestCase;

/**
 * @author swilliams
 *
 */
public class BasicTests {
    public BasicTests() {
    }
    public static void main(String [] args) {
	BasicTests tst = new BasicTests();
	tst.test();
    }
    //@Test
    public void test() {
	setUp();
	Itest t = new test();
	org.xbig.base.InstancePointer ipn = new org.xbig.base.InstancePointer(0);
	org.xbig.base.BytePointer bpn = new org.xbig.base.BytePointer(ipn);
	message(&quot;	BytePointer bp = t.doWhatever(bpn);&quot;);
	BytePointer bp = t.doWhatever(bpn);
	message(&quot;	if (bp.longValue() == 0L) message(\&quot;Got a Null!\&quot;);&quot;);
	if (bp.object.pointer == 0L) message(&quot;Got a Null!&quot;);
	message(&quot;	t.setString(\&quot;Hi\&quot;);&quot;);
	t.setString(&quot;Hi&quot;);
	message(&quot;	message(t.getString());&quot;);
	message(t.getString());
	message(&quot;	t.setString(bpn);&quot;);
	t.setStringP(t.mkStringP(&quot;wow!&quot;));
	message(&quot;	bp = t.getCString();&quot;);
	bp = t.getCString();
	message(&quot;	if (bp.object.pointer() == 0L) message(\&quot;Got a Null!\&quot;);&quot;);
	if (bp.object.pointer == 0L) message(&quot;Got a Null!&quot;);
	message(&quot;doWhatever(null) isNull:&quot;);
	t.doWhatever(bpn);
	message(&quot;isNull:&quot;+t.isNull());
	t.doWhatever(t.dupcString(&quot;Hi again!&quot;));
	message(&quot;isNull:&quot;+t.isNull());

	message(&quot;isTestNull:&quot;+t.isTestNull(t));
	message(&quot;isTestNull:&quot;+t.isTestNull(null));

	Itest tn = t.getTest();
	message(&quot;getTest:&quot;+(tn==null)+&quot;(test)tn.object.pointer:&quot;+((test)tn).object.pointer);
	message(&quot;tn == null: &quot;+(tn == null));
	tn = t.getTestNull();
	message(&quot;tn == null: &quot;+(tn == null));
	if (tn != null)
	    message(&quot;isTestNull:&quot;+(tn==null)+&quot;(test)tn.object.pointer:&quot;+((test)tn).object.pointer);

	message(&quot;new ByteVector&quot;);
	ByteVector bv = new ByteVector();
	message(&quot;mkByteVector()&quot;);
	IByteVector ibv = test.mkByteVector();
	ibv.reserve(20);
	ibv.push_back((byte)'h');
	ibv.push_back((byte)'i');
	bv.reserve(20);
	bv.push_back((byte)'h');
	bv.push_back((byte)'i');
	message(&quot;byte[] ba = byteArray&quot;);
	byte[] ba = ByteArray.byteArray(bv);
	message(&quot;ba: &quot;+(char)ba[0]+(char)ba[1]);
	byte[] iba = ByteArray.byteArray(ibv);
	message(&quot;iba: &quot;+(char)iba[0]+(char)iba[1]);

	bv = ByteArray.byteVector(ba);
	// ByteVector bv2 = new ByteVector();
	IByteVector bv2 = ibv; // ByteArray.byteVector(new byte[20]);
	// test.bvDouble(bv, bv2);

	byte[] binit = {0, 1, 2, 3, 4, 5, 6, 7};
	message(&quot;Copy to bv2&quot;);
	ByteArray.copy(binit, bv2);
	byte[] bnn = new byte[40];
	message(&quot;Copy bv -&gt; bnn&quot;);
	bnn = ByteArray.copy(bv2, bnn);
	message(&quot;try to get bv2 data&quot;);
	byte[] bn = ByteArray.byteArray(bv2);
	message(&quot;bn: &quot;+(char)bn[0]+(char)bn[1]);
	
	message(&quot;Starting bp copying:static255()&quot;);
	BytePointer cbp = ByteArray.static255();
	message(&quot;copy(binit, cbp, 8)&quot;);
	ByteArray.copy(binit, cbp, 8);
	message(&quot;if bad&quot;);
	if (ByteArray.static255bad()) message(&quot;static255 corrupted!&quot;);
	byte[] binit2 = {8,8,8,8,8,8,8,8,9};
	message(&quot;copy(cbp, 8, binit2)&quot;);
	ByteArray.copy(cbp, 8, binit2);
	if (ByteArray.static255bad()) message(&quot;static255 corrupted!&quot;);
	if (binit2[4] != 4) message(&quot;binit2 did not get proper results:&quot;+(char)binit2[4]); else
	    message(&quot;binit2 got the data we were looking for.&quot;);
	message(&quot;Done with bp copying.&quot;);
    }
    
    byte[] buffer = null;
    
    /**
     * Sets up the test fixture.
     *
     * Called before every test case method.
     */
    protected void setUp() {
	message(&quot;Starting Setup&quot;);
    }
    
    protected void setUp(String fname, String mime) {
    }
    
    /**
     * Tests 
     */
    public void testSomething() {	
	try {	    
	    // fail(&quot;Should raise a ProductNotFoundException&quot;);	    
	} catch(Exception expected) {
	    // successful test
	}
    }
    /**
     * Tears down the test fixture.
     *
     * Called after every test case method.
     */
    protected void tearDown() {
	// release objects under test here, if necessary
	message(&quot;done&quot;);
    }
    
    public void message(String msg) {
	System.err.println(msg);
    }
    public void error(int err, String msg) {
	System.err.printf(&quot;%d %s\n&quot;, err, msg);
    }
}
&lt;/code&gt;</pre>
</div>
<div title="JavaGlue.05.2 JavaGlue Diagrams" modifier="StephenWilliams" created="201103090845" modified="201103091858" tags="AnDevCon2011 JavaGlue Diagram" changecount="3">
<pre>!JavaGlue Build Diagram
[img[JavaGlue Build Diagram|BuildingAndRunningJavaGlueCode.png]]
</pre>
</div>
<div title="JavaGlue.06 JavaGlue Build System" modifier="StephenWilliams" created="201103091053" modified="201103091058" tags="AnDevCon2011 JavaGlue CMake" changecount="2">
<pre>!Host vs. Embedded Development
For a variety of reasons, it is a best practice to write as much code as possible to run cross-platform.  With respect to Android, this means that the C++ code should run on MacOS X / Linux (and Windows too if you like) and the first layer of Java code should work in &quot;native Java&quot; along with Dalvik.  Since there are very few Android-specific features that native Android C/C++ can get to, this is usually not too difficult.  In the case of our recent project, we had significant C++ code in several layers that needed to be used on Android, iOS, Qt Windows, and Qt MacOSX.

To accomplish this, and to make the use of JavaGlue efficiently, we chose to use CMake as a cross-platform build system.  We also wrote generic Java code that used much of the C++ layer so that this could all be debugged on the host before running on Dalvik/Android.  After solving many problems, and recently porting to NDK5, we have used this extensively.  We do not use the NDK build system, only the cross-compilation tools, libraries, and headers.  Getting this right required a thorough analysis of arguments for compiling and linking shared libraries for Android on multiple architectures, MacOSX, and Linux.  Windows building is partially solved (we build the C++ code using CMake-generated Visual Studio projects), but we don't currently build the Java/JavaGlue portion of the system there as there is no interest.
!CMake, Two-Pass Builds, Android
We use CMake with custom platform definitions for Android, conditionalized explicit steps to run JavaGlue code generation, build all of the C++ code to a shared library and the Java binding code to a JAR file, and execute some regression tests.  The Android Eclipse project then references the resulting Jar file.  CMake is very nice, and seems at first to have great documentation, however doing anything beyond trivial projects suffers from a lack of good examples.  Furthermore, code generation systems like JavaGlue give most build systems fits.  The main problem is that new C++ and Java source files can appear (or disappear) from the source tree during build because of changes to the C++ headers.  Solving this in a way that mostly preserved full dependency based building was a key success.

The way this was accomplished was by running the CMake build system generation step a second time when necessary.  A driver Makefile is used to run a first pass.  If JavaGlue code generation is required, a flag file is removed, causing the rest of the first built to short-circuit.  The Makefile reacts to the missing flag file by running a second CMake generate pass which picks up the file changes through standard CMake globbing, and then a make with the same parameters is run again.  Generally, we maintain the ability to run a local host and Android build without a clean.  A 'make Clean' wipe is needed after certain types of changes.

[[JavaGlue.12 CMake]] describes CMake in a little more depth.  The example build system uses [[cpp-project-template|https://code.google.com/p/cpp-project-template/]] as a base build environment, with CMake used in Makefile mode and our driver.  Scripts that we use for installing needed apt packages in Ubuntu or Macports packages on MacOSX are included.  Note that we install all development Macports packages with +universal so that we can produce both 32-bit and 64-bit libraries.

The main JavaGlue / XBiG system is in tools/xbig.  Any Java binding related code, Java or C++, goes in bindings/java, as does the main JavaGlue CMakeLists.txt script.  CMake has very good support for out-of-source builds, so we always build in build/.  Be careful not to run 'cmake' outside of build/ as the cache is sticky and stubborn.  There is a script to cleanup mistakes.  Currently, we use subdirectories of build for host vs. Android, etc., but the current example project does not.  This will likely change in the next release.</pre>
</div>
<div title="JavaGlue.07 Memory Management" modifier="StephenWilliams" created="201103080826" modified="201103090901" tags="AnDevCon2011 JavaGlue" changecount="5">
<pre>!Memory Management
A JavaGlue generated Java proxy class contains:
* a pointer to a C++ object, 
* a flag that indicates how the object was allocated, 
* methods to call all C++ static and member methods through generated JNI code, and 
* some utility methods that are not normally used directly.
A &quot;JavaGlue object&quot; consists of an instance of the C++ class and the corresponding Java proxy class instance that holds a pointer.  The JavaGlue object can be created in three ways:
* By allocation in Java (SomeCPPClass scc = new SomeCPPClass();)
* By C++ code that returns a pointer (i.e. a &quot;factory&quot; method)
* By C++ code that returns an object by value (factory method returning by value, which involves a copy constructor)
When a JavaGlue object is created by allocation in Java, a flag is set in the Java object so that the object can be deleted (by calling &quot;delete()&quot;).  If not deleted explicitly (which is recommended) then the finalizer on the Java class will delete the object.  Note that finalizers may not run predictably or be guaranteed to run in a given JVM.

If an object is returned from a method by pointer, JavaGlue records the fact that C++ code &quot;owns&quot; the allocation of that object and will refuse to call the destructor on that object by throwing an exception.  This is similar to C++ allocation / deallocation rules in a number of environments.  There is a Delete utility class that contains &quot;factory destructors&quot; for some cases that don't automatically end up with accessible destructors, such as byte arrays or vectors.

In C++, objects are passed to methods in one of three ways, and as return values in one of two ways:
* by value: the object is on the stack (both)
* by pointer: a pointer to the object is on the stack (both)
* by reference: a pointer to the object is on the stack, but it is always interpreted dereferenced and cannot be null (only as a method parameter)
An object returned by value is a copy of the object that the method returned, which typically no longer exists.  In this case, there is a potential quandary.  Because Java passes everything but scalar constants as references, there would be no obvious difference between an object returned by value vs. a pointer to an object.  To avoid all confusion and better match the actual semantics involved, the XBiG authors implemented the return by value case a return of void with an extra first parameter that is an &quot;out&quot; variable.  This requires the caller to first construct an object matching the return type needed, then pass this as the first parameter.  The reference to this is passed to the generated C method which invokes the copy constructor to the Java-allocated object.  This creates the requirement that the object have a usable-from-Java constructor (not the case for a naked parameterized template type), and that the Java application code delete the object later.

JavaGlue creates a normal Java class that acts as an &quot;interface&quot; class (&quot;I&quot; followed by the class name) and, usually, a Java class which is a subclass of the interface class.  The interface class holds references to static class methods.  There is also a global interface class for public functions that are not class members.  In cases where there is no constructor available to Java, only the &quot;interface&quot; (&quot;I&quot; class) is generated.  While Java cannot create an instance of these classes, a reference (holding a pointer) can be returned from a C++ method and later passed as a parameter.
</pre>
</div>
<div title="JavaGlue.08 Utility Methods" modifier="StephenWilliams" created="201103090845" modified="201103091011" tags="AnDevCon2011 JavaGlue" changecount="3">
<pre>XBiG already included good string conversion methods.  JavaGlue adds byte array / byte vector copy/allocate methods for a number of useful cases, plus memset.
&lt;code Java&gt;
public class ByteArray {
    // ByteArray (byte[]) / ByteVector (vector&lt;unsigned char&gt;) methods
    public static long memset(IByteVector bv, long b, long len) {
        return memsetByteVectorNative(bv, b, len);
    }
    public static native long memsetByteVectorNative(IByteVector bv, long b, long len);

    public static byte[] byteArray(IByteVector byteVector) {
	return byteArray(byteVector, false);
    }
    public static byte[] byteArray(IByteVector byteVector, boolean fullAllocation) {
	long bvn = byteVector.getInstancePointer().pointer;
	if (bvn == 0L) return null; // Just pass it on
	return byteArrayNative(bvn, fullAllocation);
    }
    public static native byte[] byteArrayNative(long ptr, boolean fullAllocation);

    public static ByteVector byteVector(byte[] bytes) {
	return byteVector(bytes, 0);
    }
    public static ByteVector byteVector(byte[] bytes, long reserve) {
	long _returnObjPtr = byteVectorNative(bytes, reserve);
	return new ByteVector(new InstancePointer(_returnObjPtr));
    }
    public static native long byteVectorNative(byte[] bytes, long reserve);

    public static byte[] copy(IByteVector bv, byte[] ba) {
	long bvn = bv.getInstancePointer().pointer;
	if (bvn == 0L) return null; // Just pass it on
	return copyNativebv2ba(bvn, ba);
    }
    public static native byte[] copyNativebv2ba(long bv, byte[] ba);

    public static ByteVector copy(byte[] ba, IByteVector bv) {
	long bvn = bv.getInstancePointer().pointer;
	if (bvn == 0L) return null; // Just pass it on
	long _returnObjPtr = copyNativeba2bv(ba, bvn);
	return new ByteVector(new InstancePointer(_returnObjPtr));
    }
    public static native long copyNativeba2bv(byte[] ba, long bv);

    // ByteArray / BytePointer methods
    public static long memset(BytePointer bp, long b, long len) {
	long bpn = bp.getInstancePointer().pointer;
        return memsetBytePointerNative(bpn, b, len);
    }
    public static native long memsetBytePointerNative(long bp, long b, long len);

    public static byte[] byteArray(BytePointer bp, long size) {
	long bpn = bp.getInstancePointer().pointer;
	return byteArrayNativebp(bpn, size);
    }
    public static native byte[] byteArrayNativebp(long bp, long size);

    public static BytePointer bytePointer(byte[] bytes) {
	return bytePointer(bytes, bytes.length);
    }
    public static BytePointer bytePointer(byte[] bytes, long size) {
	return bytePointerNative(bytes, size);
    }
    public static native BytePointer bytePointerNative(byte[] bytes, long size);

    // Copy from byte array to byte pointer up to size or ba.length.
    // Return amount of data written.
    public static long copy(byte[] ba, BytePointer bp, long size) {
	long bpn = bp.getInstancePointer().pointer;
	if (bpn == 0) error(0, &quot;Bad bp instancePointer == null&quot;);
	return copyNativeba2bp(ba, bpn, size);
    }
    public static native long copyNativeba2bp(byte[] ba, long bp, long size);

    // Copy from byte pointer to array up to size or ba.length.
    // Return amount of data written.
    public static long copy(BytePointer bp, long size, byte[] ba) {
	long bpn = bp.getInstancePointer().pointer;
	if (bpn == 0) error(0, &quot;Bad bp instancePointer == null&quot;);
	if (ba == null) error(0, &quot;Bad byteArray == null!&quot;);
	return copyNativebp2ba(bpn, size, ba);
    }
    public static native long copyNativebp2ba(long bp, long size, byte[] ba);

    // Like the last copy except that the byte array might be reallocated,
    // always use return value to overwrite ba references;
    public static byte[] copyRealloc(BytePointer bp, long size, byte[] ba) {
	long bpn = bp.getInstancePointer().pointer;
	return copyNativebp2baRealloc(bpn, size, ba);
    }
    public static native byte[] copyNativebp2baRealloc(long bp, long size, byte[] ba);
}
&lt;/code&gt;
This provides some frequently needed template instantiations, plus an accessible way to delete allocated objects.
The xbig_* methods are used in C/C++-&gt;Java code.  It turns out to be difficult to successfully look up Java methods from C without using these methods.  The default JVM reference doesn't have a complete class loader so all lookups fail.
jni_base.h:
&lt;code C++&gt;
void Delete::byteVector(base::ByteVector* bv) { delete bv; }
void Delete::stringVector(base::StringVector* sv) { delete sv; }
void Delete::vectorByteVector(base::VectorByteVector* vbv) { delete vbv; }
void Delete::mapStringByteVector(base::MapStringByteVector* msbv) { delete msbv; }
void Delete::mapLongByteVector(base::MapLongByteVector* mlbv) { delete mlbv; }
void Delete::mapStringString(base::MapStringString* mss) { delete mss; }

JNIEXPORT JNIEnv* Xbig_GetEnv();
JNIEXPORT jmethodID Xbig_cpath2MID(const char* cpath, const char* meth, const char* sig);
JNIEXPORT jmethodID Xbig_cpath2MIDenv(JNIEnv* env, const char* cpath, const char* meth, const char* sig);
JNIEXPORT jfieldID Xbig_cpath2FIDenv(JNIEnv* env, const char* cpath, const char* field, const char* sig);
JNIEXPORT jmethodID Xbig_obj2MID(jobject obj, const char* meth, const char* sig);
JNIEXPORT jmethodID Xbig_obj2MIDenv(JNIEnv* env, jobject obj, const char* meth, const char* sig);
&lt;/code&gt;
basedelete.h:
&lt;code C++&gt;
#include &lt;jni.h&gt;
#include &lt;string&gt;
#include &lt;vector&gt;
#include &lt;map&gt;

namespace base {
typedef std::vector&lt;unsigned char&gt; ByteVector;
typedef std::vector&lt;std::string&gt; StringVector;
typedef std::vector&lt;ByteVector&gt; VectorByteVector;
typedef std::map&lt;std::string, ByteVector&gt; MapStringByteVector;
typedef std::map&lt;long, ByteVector&gt; MapLongByteVector;
typedef std::map&lt;std::string, std::string&gt; MapStringString;
}
class Delete {
  public:
    static void byteVector(base::ByteVector* bv);
    static void stringVector(base::StringVector* sv);
    static void vectorByteVector(base::VectorByteVector* vbv);
    static void mapStringByteVector(base::MapStringByteVector* msbv);
    static void mapLongByteVector(base::MapLongByteVector* mlbv);
    static void mapStringString(base::MapStringString* mss);
};
&lt;/code&gt;


</pre>
</div>
<div title="JavaGlue.10 Internals" modifier="StephenWilliams" created="201103090847" modified="201103091128" tags="AnDevCon2011 JavaGlue" changecount="4">
<pre>JavaGlue (and XBiG) uses Doxygen to parse C++ header files, producing an XML description of all types, methods, members, and variables.  This is processed in a series of stages by an Ant-driven XSL engine.  After producing an intermediate mapping, a Java generation and a C++ generation pass are made.  At this point, the original C/C++ code and the generated C++ code can be compiled into a shared library.  The generated java code can be added to an Eclipse project, or just compiled into a JAR file which can be referenced by an Eclipse project.  Once the Java code compiles, the run settings must run the application from a directory and environment where the shared library will be found.  For an Android project, this means having the shared library under the correct libs/ARCH/ directory and the JAR file (if that route is taken) is in the lib/ directory.

Example code produced from the examples above:
Itest4.java:
&lt;code Java&gt;
package org.xbig;

import org.xbig.base.*;
public interface Itest4 extends INativeObject, org.xbig.Itest, org.xbig.Itest3 {

}
&lt;/code&gt;
test4.java:
&lt;code Java&gt;

package org.xbig;

import org.xbig.base.*;
public class test4 extends org.xbig.base.NativeObject implements org.xbig.Itest4 {
static { System.loadLibrary(&quot;xbig&quot;); } 
        
	/**
	 * 
	 * This constructor is public for internal useage only!
	 * Do not use it!
	 * 
	 */
	public test4(org.xbig.base.InstancePointer p) {
		super(p);
	}

	/**
	 * 
	 * Creates a Java wrapper object for an existing C++ object.
	 * If remote is set to 'true' this object cannot be deleted in Java.
	 * 
	 */
	protected test4(org.xbig.base.InstancePointer p, boolean remote) {
		super(p, remote);
	}

    /**
     * Allows creation of Java objects without C++ objects.
     * 
     * @see org.xbig.base.WithoutNativeObject
     * @see org.xbig.base.INativeObject#disconnectFromNativeObject()
     */
	public test4(org.xbig.base.WithoutNativeObject val) {
		super(val);
	}

	public void delete() {
		if (this.remote) {
	       throw new RuntimeException(&quot;can't dispose object created by native library&quot;);
	    }

		if(!this.deleted) {
		    __delete(object.pointer);
		    this.deleted = true;
		   	this.object.pointer = 0;
		}
	}

	public void finalize() {
		if(!this.remote &amp;&amp; !this.deleted) {
			delete();
		}
	}
	
			
	private final native void __delete(long _pointer_);	



          /** **/
    public test4() {
         super( new org.xbig.base.InstancePointer(__createtest4()), false);
    }

    private native static long __createtest4();

    /** **/
    public BytePointer doWhatever(BytePointer pp) {
        
	return new BytePointer(new InstancePointer(_doWhatever__cp(this.object.pointer, pp.object.pointer)));
    }

    private native long _doWhatever__cp(long _pointer_, long pp);

    /** **/
    public StringPointer mkStringP(String s) {
        
	return new StringPointer(new InstancePointer(_mkStringP__sv(this.object.pointer, s)));
    }

    private native long _mkStringP__sv(long _pointer_, String s);

    /** **/
    public void setString(String s) {
        _setString__sv(this.object.pointer, s);
    }

    private native void _setString__sv(long _pointer_, String s);

    /** **/
    public void setStringP(StringPointer s) {
        _setStringP__sp(this.object.pointer, s.object.pointer);
    }

    private native void _setStringP__sp(long _pointer_, long s);

    /** **/
    public String getString() {
        
	return _getString(this.object.pointer);
    }

    private native String _getString(long _pointer_);

    /** **/
    public BytePointer getCString() {
        
	return new BytePointer(new InstancePointer(_getCString(this.object.pointer)));
    }

    private native long _getCString(long _pointer_);

    /** **/
    public BytePointer dupcString(String s) {
        
	return new BytePointer(new InstancePointer(_dupcString__sv(this.object.pointer, s)));
    }

    private native long _dupcString__sv(long _pointer_, String s);

    /** **/
    public boolean isNull() {
        
	return _isNull(this.object.pointer);
    }

    private native boolean _isNull(long _pointer_);

    /** **/
    public boolean isTestNull(org.xbig.Itest tt) {
        
	return _isTestNull__testp(this.object.pointer, tt==null ? 0L : tt.getInstancePointer().pointer);
    }

    private native boolean _isTestNull__testp(long _pointer_, long tt);

    /** **/
    public boolean isTest(org.xbig.Itest tt) {
        
	return _isTest__testv(this.object.pointer, tt==null ? 0L : tt.getInstancePointer().pointer);
    }

    private native boolean _isTest__testv(long _pointer_, long tt);

    /** **/
    public org.xbig.Itest getTest() {
        long _returnObjPtr;
	return (_returnObjPtr=_getTest(this.object.pointer)) == 0L ? null :
	  new org.xbig.test(new InstancePointer(_returnObjPtr));
    }

    private native long _getTest(long _pointer_);

    /** **/
    public org.xbig.Itest getTestNull() {
        long _returnObjPtr;
	return (_returnObjPtr=_getTestNull(this.object.pointer)) == 0L ? null :
	  new org.xbig.test(new InstancePointer(_returnObjPtr));
    }

    private native long _getTestNull(long _pointer_);

    /** **/
    public static org.xbig.base.IByteVector mkByteVector() {
        long _returnObjPtr;
	return (_returnObjPtr=_mkByteVector()) == 0L ? null :
	  new org.xbig.base.ByteVector(new InstancePointer(_returnObjPtr));
    }

    private native static long _mkByteVector();

    /** **/
    public static void bvDouble(org.xbig.base.IByteVector a1, org.xbig.base.IByteVector a2) {
        _bvDouble__base_ByteVectorvbase_ByteVectorv( a1.getInstancePointer().pointer,  a2.getInstancePointer().pointer);
    }

    private native static void _bvDouble__base_ByteVectorvbase_ByteVectorv(long a1, long a2);

    /** **/
    public VoidPointer getP3() {
         return new VoidPointer(new InstancePointer(_getP3(this.object.pointer)));
    }

    private native long _getP3(long _pointer_);

    /** **/
    public int getx() {
        
	return _getx(this.object.pointer);
    }

    private native int _getx(long _pointer_);

    /** **/
    public void setx(int _jni_value_) {
        _setx(this.object.pointer, _jni_value_);
    }

    private native void _setx(long _pointer_, int _jni_value_);

    /** **/
    public float gety() {
        
	return _gety(this.object.pointer);
    }

    private native float _gety(long _pointer_);

    /** **/
    public void sety(float _jni_value_) {
        _sety(this.object.pointer, _jni_value_);
    }

    private native void _sety(long _pointer_, float _jni_value_);

    /** **/
    public BytePointer getp() {
        
	return new BytePointer(new InstancePointer(_getp(this.object.pointer)));
    }

    private native long _getp(long _pointer_);

    /** **/
    public void setp(BytePointer _jni_value_) {
        _setp(this.object.pointer, _jni_value_.object.pointer);
    }

    private native void _setp(long _pointer_, long _jni_value_);

    /** **/
    public boolean getisNullFlag() {
        
	return _getisNullFlag(this.object.pointer);
    }

    private native boolean _getisNullFlag(long _pointer_);

    /** **/
    public void setisNullFlag(boolean _jni_value_) {
        _setisNullFlag(this.object.pointer, _jni_value_);
    }

    private native void _setisNullFlag(long _pointer_, boolean _jni_value_);

}
&lt;/code&gt;
class_org_xbig_test4.cpp:
&lt;code C++&gt;
#ifdef WIN32
	// disable warnings
	#pragma warning (disable : 4267) // conversion from 'size_t' to 'jint'
#else

#endif


// use base library for cpp2j
#include &quot;jni_base_all.h&quot;

// import declaration of all functions
#include &quot;class_org_xbig_test4.h&quot;

// import header files of original library
#include &lt;test.h&gt;



/*
 * Class:      org.xbig.test4
 * Method:     test4()
 * Type:       constructor
 * Definition: test4::test4
 * Signature:  ()V
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1_1createtest4 (
  JNIEnv* _jni_env_, /* interface pointer */
  jclass _jni_class_  /* class pointer */
)
{
   // constructor of class test4 
   
   // parameter conversions 
   
   // create new instance of class test4 
   test4* _cpp_this = new test4(); 
   
   // return casted pointer 
   jlong _jni_pointer_ = reinterpret_cast&lt;jlong&gt;(_cpp_this); 
   return _jni_pointer_;
} /* test4::test4 */


/*
 * Class:      org.xbig.test4
 * Method:     doWhatever()
 * Type:       non-virtual method
 * Definition: char* test::doWhatever
 * Signature:  (C)C
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1doWhatever_1_1cp (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jlong pp
)
{
   // parameter conversions 
  char* _cpp_pp = reinterpret_cast&lt;char*&gt;(pp); 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   char* _cpp_result = _cpp_this-&gt;doWhatever(_cpp_pp) ; 
   return reinterpret_cast&lt;jlong&gt;(_cpp_result);
} /* char* test::doWhatever */


/*
 * Class:      org.xbig.test4
 * Method:     mkStringP()
 * Type:       non-virtual method
 * Definition: std::string* test::mkStringP
 * Signature:  (Ljava/lang/String;)Ljava/lang/String;
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1mkStringP_1_1sv (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jstring s
)
{
   // parameter conversions 
  std::string _cpp_s = &quot;&quot;; org::xbig::jni::to_stdstring(_jni_env_, s, _cpp_s); // calls c-tor only. Not operator= .; 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   std::string* _cpp_result = _cpp_this-&gt;mkStringP(_cpp_s) ; 
   return reinterpret_cast&lt;jlong&gt;(_cpp_result);
} /* std::string* test::mkStringP */


/*
 * Class:      org.xbig.test4
 * Method:     setString()
 * Type:       non-virtual method
 * Definition: void test::setString
 * Signature:  (Ljava/lang/String;)V
 */

JNIEXPORT void JNICALL Java_org_xbig_test4__1setString_1_1sv (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jstring s
)
{
   // parameter conversions 
  std::string _cpp_s = &quot;&quot;; org::xbig::jni::to_stdstring(_jni_env_, s, _cpp_s); // calls c-tor only. Not operator= .; 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   _cpp_this-&gt;setString(_cpp_s);
} /* void test::setString */


/*
 * Class:      org.xbig.test4
 * Method:     setStringP()
 * Type:       non-virtual method
 * Definition: void test::setStringP
 * Signature:  (Ljava/lang/String;)V
 */

JNIEXPORT void JNICALL Java_org_xbig_test4__1setStringP_1_1sp (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jlong s
)
{
   // parameter conversions 
  std::string* _cpp_s = reinterpret_cast&lt;std::string*&gt;(s); 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   _cpp_this-&gt;setStringP(_cpp_s);
} /* void test::setStringP */


/*
 * Class:      org.xbig.test4
 * Method:     getString()
 * Type:       non-virtual method
 * Definition: std::string test::getString
 * Signature:  ()Ljava/lang/String;
 */

JNIEXPORT jstring JNICALL Java_org_xbig_test4__1getString (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   const std::string _cpp_result = _cpp_this-&gt;getString() ; 
   return org::xbig::jni::to_jstring(_jni_env_, _cpp_result);
} /* std::string test::getString */


/*
 * Class:      org.xbig.test4
 * Method:     getCString()
 * Type:       non-virtual method
 * Definition: char* test::getCString
 * Signature:  ()C
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1getCString (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   char* _cpp_result = _cpp_this-&gt;getCString() ; 
   return reinterpret_cast&lt;jlong&gt;(_cpp_result);
} /* char* test::getCString */


/*
 * Class:      org.xbig.test4
 * Method:     dupcString()
 * Type:       non-virtual method
 * Definition: char* test::dupcString
 * Signature:  (Ljava/lang/String;)C
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1dupcString_1_1sv (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jstring s
)
{
   // parameter conversions 
  std::string _cpp_s = &quot;&quot;; org::xbig::jni::to_stdstring(_jni_env_, s, _cpp_s); // calls c-tor only. Not operator= .; 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   char* _cpp_result = _cpp_this-&gt;dupcString(_cpp_s) ; 
   return reinterpret_cast&lt;jlong&gt;(_cpp_result);
} /* char* test::dupcString */


/*
 * Class:      org.xbig.test4
 * Method:     isNull()
 * Type:       non-virtual method
 * Definition: bool test::isNull
 * Signature:  ()Z
 */

JNIEXPORT jboolean JNICALL Java_org_xbig_test4__1isNull (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   const bool _cpp_result = _cpp_this-&gt;isNull() ; 
   return _cpp_result ? 1 : 0;
} /* bool test::isNull */


/*
 * Class:      org.xbig.test4
 * Method:     isTestNull()
 * Type:       non-virtual method
 * Definition: bool test::isTestNull
 * Signature:  (test)Z
 */

JNIEXPORT jboolean JNICALL Java_org_xbig_test4__1isTestNull_1_1testp (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jlong tt
)
{
   // parameter conversions 
  test* _cpp_tt = reinterpret_cast&lt; test* &gt;(tt); 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   const bool _cpp_result = _cpp_this-&gt;isTestNull(_cpp_tt) ; 
   return _cpp_result ? 1 : 0;
} /* bool test::isTestNull */


/*
 * Class:      org.xbig.test4
 * Method:     isTest()
 * Type:       non-virtual method
 * Definition: bool test::isTest
 * Signature:  (test)Z
 */

JNIEXPORT jboolean JNICALL Java_org_xbig_test4__1isTest_1_1testv (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jlong tt
)
{
   // parameter conversions 
  test* _cpp_tt = reinterpret_cast&lt; test* &gt;(tt); 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   const bool _cpp_result = _cpp_this-&gt;isTest(*_cpp_tt) ; 
   return _cpp_result ? 1 : 0;
} /* bool test::isTest */


/*
 * Class:      org.xbig.test4
 * Method:     getTest()
 * Type:       non-virtual method
 * Definition: test* test::getTest
 * Signature:  ()test
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1getTest (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   const test* _cpp_result = _cpp_this-&gt;getTest() ; 
   return reinterpret_cast&lt;jlong&gt;(_cpp_result);
} /* test* test::getTest */


/*
 * Class:      org.xbig.test4
 * Method:     getTestNull()
 * Type:       non-virtual method
 * Definition: test* test::getTestNull
 * Signature:  ()test
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1getTestNull (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   const test* _cpp_result = _cpp_this-&gt;getTestNull() ; 
   return reinterpret_cast&lt;jlong&gt;(_cpp_result);
} /* test* test::getTestNull */


/*
 * Class:      org.xbig.test4
 * Method:     mkByteVector()
 * Type:       static method
 * Definition: static base::ByteVector&amp; test::mkByteVector
 * Signature:  ()base_ByteVector
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1mkByteVector (
  JNIEnv* _jni_env_, /* interface pointer */
  jclass _jni_class_  /* class pointer */
)
{
   // static method of class test4 with return value 
   // parameter conversions 
   
   // call library method 
   const base::ByteVector* _cpp_result = &amp; test4::mkByteVector(); 
   return reinterpret_cast&lt;jlong&gt;(_cpp_result);
} /* static base::ByteVector&amp; test::mkByteVector */


/*
 * Class:      org.xbig.test4
 * Method:     bvDouble()
 * Type:       static method
 * Definition: static void test::bvDouble
 * Signature:  (base_ByteVectorbase_ByteVector)V
 */

JNIEXPORT void JNICALL Java_org_xbig_test4__1bvDouble_1_1base_1ByteVectorvbase_1ByteVectorv (
  JNIEnv* _jni_env_, /* interface pointer */
  jclass _jni_class_,  /* class pointer */
  jlong a1, 
  jlong a2
)
{
   // static method of class test4 without return value 
   // parameter conversions 
  base::ByteVector* _cpp_a1 = reinterpret_cast&lt; base::ByteVector* &gt;(a1);
  base::ByteVector* _cpp_a2 = reinterpret_cast&lt; base::ByteVector* &gt;(a2); 
   
   // call library method 
   test4::bvDouble(*_cpp_a1, *_cpp_a2);
} /* static void test::bvDouble */


/*
 * Class:      org.xbig.test4
 * Method:     getP3()
 * Type:       non-virtual method
 * Definition: void* test3::getP3
 * Signature:  ()V
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1getP3 (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   void* _cpp_result = _cpp_this-&gt;getP3() ; 
   return reinterpret_cast&lt;jlong&gt;(_cpp_result);
} /* void* test3::getP3 */


/*
 * Class:      org.xbig.test4
 * Method:     __delete()
 * Type:       destructor
 * Definition: test4::__delete
 * Signature:  ()V
 */

JNIEXPORT void JNICALL Java_org_xbig_test4__1_1delete (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // destructor of class test4 
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   // delete object if it exists 
   if(_cpp_this != NULL) delete _cpp_this;
} /* test4::__delete */


/*
 * Class:      org.xbig.test4
 * Method:     getx()
 * Type:       getter for public attribute
 * Definition: int test::x
 * Signature:  ()I
 */

JNIEXPORT jint JNICALL Java_org_xbig_test4__1getx (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   const int _cpp_result = _cpp_this-&gt;x; 
   return _cpp_result;
} /* int test::x */


/*
 * Class:      org.xbig.test4
 * Method:     setx()
 * Type:       setter for public attribute
 * Definition: int test::x
 * Signature:  (I)V
 */

JNIEXPORT void JNICALL Java_org_xbig_test4__1setx (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jint _jni_value_
)
{
   // parameter conversions 
  int _cpp__jni_value_ = _jni_value_; 
   
   // cast pointer to C++ object 
   test4* _cpp_this =reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   _cpp_this-&gt;x = _cpp__jni_value_;
} /* int test::x */


/*
 * Class:      org.xbig.test4
 * Method:     gety()
 * Type:       getter for public attribute
 * Definition: float test::y
 * Signature:  ()F
 */

JNIEXPORT jfloat JNICALL Java_org_xbig_test4__1gety (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   const float _cpp_result = _cpp_this-&gt;y; 
   return _cpp_result;
} /* float test::y */


/*
 * Class:      org.xbig.test4
 * Method:     sety()
 * Type:       setter for public attribute
 * Definition: float test::y
 * Signature:  (F)V
 */

JNIEXPORT void JNICALL Java_org_xbig_test4__1sety (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jfloat _jni_value_
)
{
   // parameter conversions 
  float _cpp__jni_value_ = _jni_value_; 
   
   // cast pointer to C++ object 
   test4* _cpp_this =reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   _cpp_this-&gt;y = _cpp__jni_value_;
} /* float test::y */


/*
 * Class:      org.xbig.test4
 * Method:     getp()
 * Type:       getter for public attribute
 * Definition: char* test::p
 * Signature:  ()C
 */

JNIEXPORT jlong JNICALL Java_org_xbig_test4__1getp (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   char* _cpp_result = _cpp_this-&gt;p; 
   return reinterpret_cast&lt;jlong&gt;(_cpp_result);
} /* char* test::p */


/*
 * Class:      org.xbig.test4
 * Method:     setp()
 * Type:       setter for public attribute
 * Definition: char* test::p
 * Signature:  (C)V
 */

JNIEXPORT void JNICALL Java_org_xbig_test4__1setp (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jlong _jni_value_
)
{
   // parameter conversions 
  char* _cpp__jni_value_ = reinterpret_cast&lt;char*&gt;(_jni_value_); 
   
   // cast pointer to C++ object 
   test4* _cpp_this =reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   _cpp_this-&gt;p = _cpp__jni_value_;
} /* char* test::p */


/*
 * Class:      org.xbig.test4
 * Method:     getisNullFlag()
 * Type:       getter for public attribute
 * Definition: bool test::isNullFlag
 * Signature:  ()Z
 */

JNIEXPORT jboolean JNICALL Java_org_xbig_test4__1getisNullFlag (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_ /* C++ pointer */
)
{
   // parameter conversions 
   
   // cast pointer to C++ object 
   test4* _cpp_this = reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   const bool _cpp_result = _cpp_this-&gt;isNullFlag; 
   return _cpp_result ? 1 : 0;
} /* bool test::isNullFlag */


/*
 * Class:      org.xbig.test4
 * Method:     setisNullFlag()
 * Type:       setter for public attribute
 * Definition: bool test::isNullFlag
 * Signature:  (Z)V
 */

JNIEXPORT void JNICALL Java_org_xbig_test4__1setisNullFlag (
  JNIEnv* _jni_env_, /* interface pointer */
  jobject _jni_this_, /* Java object */
  jlong _jni_pointer_, /* C++ pointer */
  jboolean _jni_value_
)
{
   // parameter conversions 
  bool _cpp__jni_value_ = _jni_value_ ? true : false; 
   
   // cast pointer to C++ object 
   test4* _cpp_this =reinterpret_cast&lt;test4*&gt;(_jni_pointer_); 
   
   // call library method 
   _cpp_this-&gt;isNullFlag = _cpp__jni_value_;
} /* bool test::isNullFlag */
&lt;/code&gt;

</pre>
</div>
<div title="JavaGlue.11 Advanced JNI" modifier="StephenWilliams" created="201103090853" modified="201103092317" tags="AnDevCon2011 JavaGlue" changecount="2">
<pre></pre>
</div>
<div title="JavaGlue.12 CMake" modifier="StephenWilliams" created="201103081100" modified="201103091120" tags="AnDevCon2011 CMake JavaGlue" changecount="7">
<pre>!What is CMake?
From the manual:
&lt;&lt;&lt;
CMake is a cross-platform build system generator. Projects specify their build process with platform-independent CMake listfiles included in each directory of a source tree with the name CMakeLists.txt. Users build a project by using CMake to generate a build system for a native tool on their platform.
&lt;&lt;&lt;
CMake can be very confusing at first, especially if you only read the official manual and only have very simple projects as reference.  Here are a few words that may greatly ease the learning curve:

CMake is a meta-make system.  This means that CMake doesn't build anything but build scripts for actual build systems.  CMake can generate Makefiles, XCode projects, Visual Studio projects, and Eclipse projects, at least.  The files generated may seem a bit different than you may expect.  Mostly this is good because some nice automation and other capabilities are provided.  CMakeList.txt scripts reference other CMakeList.txt scripts in subdirectories plus they can include files that may be in a project (typically named *.cmake).  CMake relies on an installed directory of modules and other scripts that know how to find various libraries, subsystems, executables, etc.  These are invoked by requesting access to (i.e. variables to be set) standard modules, like Java.

Typical operations in CMake scripts involve finding system capabilities, setting variables, globbing for source code or data files (into variables), defining source directories &amp; files, defining libraries, and defining executables.  Dependencies can be explicitly created while many are inferred automatically.  Custom commands can be defined.  Most are used at build time, but there is some limited ability to do operations at meta-make time.  Definition of most operations is at a very high, logical level.  Only when defining a new platform or doing something beyond compile, create library, link executables do you need to work with native tool definitions, arguments, or anything platform specific.

Many CMake variables have values at meta-make time based on where they are referenced in a CMakeList.txt file.  The key examples of this are variables for the current source and current &quot;binary&quot; (i.e. build target, shadow build) directories.  Generally, a particular CMakeList.txt can only set variables for those scripts below it, so frequently things needed by one subdirectory from another are set at a higher level.  In essence, CMake at meta-make time is a functional language with a lot of built-in functionality, controled by conditionalized scripting to solve all platform-specific issues.

The resulting makefiles have absolute paths everywhere, targets that flow from the top directory down to where they need to be built, and have a default output that is very clean in the absence of errors.  A 'make VERBOSE=1' gives full detail of steps being taken.  For Make, you can still do parallel makes with -j4 (J=4 to the driver build/Makefile in the JavaGlue example project).  DEBUG is the default, use RELEASE=1 for release builds.

* http://www.cmake.org/cmake/help/cmake-2-8-docs.html
* https://code.google.com/p/cpp-project-template/

Others using CMake with Android:
https://code.google.com/p/android-cmake/
</pre>
</div>
<div title="LISP" modifier="Jonny Gerold" created="201008102233" modified="201008102252" tags="Programming" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201008102252">
<pre>* [[Books]]
**	[[SICP (Structure and Interpretation of Computer Programs)]]</pre>
</div>
<div title="LessBackupsPlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|LessBackupsPlugin|
|Description:|Intelligently limit the number of backup files you create|
|Version:|3.0.1 ($Rev: 2320 $)|
|Date:|$Date: 2007-06-18 22:37:46 +1000 (Mon, 18 Jun 2007) $|
|Source:|http://mptw.tiddlyspot.com/#LessBackupsPlugin|
|Author:|Simon Baird|
|Email:|simon.baird@gmail.com|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Description
You end up with just backup one per year, per month, per weekday, per hour, minute, and second.  So total number won't exceed about 200 or so. Can be reduced by commenting out the seconds/minutes/hours line from modes array
!!Notes
Works in IE and Firefox only.  Algorithm by Daniel Baird. IE specific code by by Saq Imtiaz.
***/
//{{{

var MINS  = 60 * 1000;
var HOURS = 60 * MINS;
var DAYS  = 24 * HOURS;

if (!config.lessBackups) {
	config.lessBackups = {
		// comment out the ones you don't want or set config.lessBackups.modes in your 'tweaks' plugin
		modes: [
			[&quot;YYYY&quot;,  365*DAYS], // one per year for ever
			[&quot;MMM&quot;,   31*DAYS],  // one per month
			[&quot;ddd&quot;,   7*DAYS],   // one per weekday
			//[&quot;d0DD&quot;,  1*DAYS],   // one per day of month
			[&quot;h0hh&quot;,  24*HOURS], // one per hour
			[&quot;m0mm&quot;,  1*HOURS],  // one per minute
			[&quot;s0ss&quot;,  1*MINS],   // one per second
			[&quot;latest&quot;,0]         // always keep last version. (leave this).
		]
	};
}

window.getSpecialBackupPath = function(backupPath) {

	var now = new Date();

	var modes = config.lessBackups.modes;

	for (var i=0;i&lt;modes.length;i++) {

		// the filename we will try
		var specialBackupPath = backupPath.replace(/(\.)([0-9]+\.[0-9]+)(\.html)$/,
				'$1'+now.formatString(modes[i][0]).toLowerCase()+'$3')

		// open the file
		try {
			if (config.browser.isIE) {
				var fsobject = new ActiveXObject(&quot;Scripting.FileSystemObject&quot;)
				var fileExists  = fsobject.FileExists(specialBackupPath);
				if (fileExists) {
					var fileObject = fsobject.GetFile(specialBackupPath);
					var modDate = new Date(fileObject.DateLastModified).valueOf();
				}
			}
			else {
				netscape.security.PrivilegeManager.enablePrivilege(&quot;UniversalXPConnect&quot;);
				var file = Components.classes[&quot;@mozilla.org/file/local;1&quot;].createInstance(Components.interfaces.nsILocalFile);
				file.initWithPath(specialBackupPath);
				var fileExists = file.exists();
				if (fileExists) {
					var modDate = file.lastModifiedTime;
				}
			}
		}
		catch(e) {
			// give up
			return backupPath;
		}

		// expiry is used to tell if it's an 'old' one. Eg, if the month is June and there is a
		// June file on disk that's more than an month old then it must be stale so overwrite
		// note that &quot;latest&quot; should be always written because the expiration period is zero (see above)
		var expiry = new Date(modDate + modes[i][1]);
		if (!fileExists || now &gt; expiry)
			return specialBackupPath;
	}
}

// hijack the core function
window.getBackupPath_mptw_orig = window.getBackupPath;
window.getBackupPath = function(localPath) {
	return getSpecialBackupPath(getBackupPath_mptw_orig(localPath));
}

//}}}

</pre>
</div>
<div title="Link color in FireFox" modifier="Pascal" created="200712141203" modified="200712141206" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712141206">
<pre>&lt;html&gt;&lt;p&gt;It seems Firefox doesn't apply styles on links while there are edited in wysiwyg mode. The default color and underline style can be changed using &lt;a href=&quot;about:config&quot;&gt;about:config&lt;/a&gt; url to change browser.underline_anchors and browser.anchor_color (this apply on all pages).

&lt;/p&gt;&lt;p&gt;Obviously, this is an ugly way to solve this problem&lt;/p&gt;&lt;/html&gt;</pre>
</div>
<div title="MPTW" modifier="MPTW" created="201004041418" modified="201009151231">
<pre>MPTW is a distribution or edition of TiddlyWiki that includes a standard TiddlyWiki core packaged with some plugins designed to improve usability and provide a better way to organise your information. For more information see http://mptw.tiddlyspot.com/.
</pre>
</div>
<div title="MatchTagsPlugin" modifier="StephenWilliams" created="200802290709" modified="201103090806" tags="systemConfig" server.type="file" server.host="http://www.tiddlytools.com" server.page.revision="201101232130" changecount="1">
<pre>/***
|Name|MatchTagsPlugin|
|Source|http://www.TiddlyTools.com/#MatchTagsPlugin|
|Documentation|http://www.TiddlyTools.com/#MatchTagsPluginInfo|
|Version|2.0.5|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|plugin|
|Description|'tag matching' with full boolean expressions (AND, OR, NOT, and nested parentheses)|
!!!!!Documentation
&gt; see [[MatchTagsPluginInfo]]
!!!!!Revisions
&lt;&lt;&lt;
2011.01.23 2.0.5 fix core tweak for TW262+: adjust code in config.filters['tag'] instead of filterTiddlers()
2010.08.11 2.0.4 in getMatchingTiddlers(), fixed sorting for descending order (e.g, &quot;-created&quot;)
| please see [[MatchTagsPluginInfo]] for additional revision details |
2008.02.28 1.0.0 initial release
&lt;&lt;&lt;
!!!!!Code
***/
//{{{
version.extensions.MatchTagsPlugin= {major: 2, minor: 0, revision: 5, date: new Date(2011,23,11)};

// store.getMatchingTiddlers() processes boolean expressions for tag matching
//    sortfield (optional) sets sort order for tiddlers - default=title
//    tiddlers (optional) use alternative set of tiddlers (instead of current store)
TiddlyWiki.prototype.getMatchingTiddlers = function(tagexpr,sortfield,tiddlers) {

	var debug=config.options.chkDebug; // abbreviation
	var cmm=config.macros.matchTags; // abbreviation
	var r=[]; // results are an array of tiddlers
	var tids=tiddlers||store.getTiddlers();
	if (tids &amp;&amp; sortfield) tids=store.sortTiddlers(tids,sortfield);
	if (debug) displayMessage(cmm.msg1.format([tids.length]));

	// try simple lookup to quickly find single tags or tags that
	// contain boolean operators as literals, e.g. &quot;foo and bar&quot;
	for (var t=0; t&lt;tids.length; t++)
		if (tids[t].isTagged(tagexpr)) r.pushUnique(tids[t]);
	if (r.length) {
		if (debug) displayMessage(cmm.msg4.format([r.length,tagexpr]));
		return r;
	}
	
	// convert expression into javascript code with regexp tests,
	// so that &quot;tag1 AND ( tag2 OR NOT tag3 )&quot; becomes
	// &quot;/\~tag1\~/.test(...) &amp;&amp; ( /\~tag2\~/.test(...) || ! /\~tag3\~/.test(...) )&quot;

	// normalize whitespace, tokenize operators, delimit with &quot;~&quot;
	var c=tagexpr.trim(); // remove leading/trailing spaces
	c = c.replace(/\s+/ig,&quot; &quot;); // reduce multiple spaces to single spaces
	c = c.replace(/\(\s?/ig,&quot;~(~&quot;); // open parens
	c = c.replace(/\s?\)/ig,&quot;~)~&quot;); // close parens
	c = c.replace(/(\s|~)?&amp;&amp;(\s|~)?/ig,&quot;~&amp;&amp;~&quot;); // &amp;&amp;
	c = c.replace(/(\s|~)AND(\s|~)/ig,&quot;~&amp;&amp;~&quot;); // AND
	c = c.replace(/(\s|~)?\|\|(\s|~)?/ig,&quot;~||~&quot;); // ||
	c = c.replace(/(\s|~)OR(\s|~)/ig,&quot;~||~&quot;); // OR
	c = c.replace(/(\s|~)?!(\s|~)?/ig,&quot;~!~&quot;); // !
	c = c.replace(/(^|~|\s)NOT(\s|~)/ig,&quot;~!~&quot;); // NOT
	c = c.replace(/(^|~|\s)NOT~\(/ig,&quot;~!~(&quot;); // NOT(
	// change tag terms to regexp tests
	var terms=c.split(&quot;~&quot;); for (var i=0; i&lt;terms.length; i++) { var t=terms[i];
		if (/(&amp;&amp;)|(\|\|)|[!\(\)]/.test(t) || t==&quot;&quot;) continue; // skip operators/parens/spaces
		if (t==config.macros.matchTags.untaggedKeyword)
			terms[i]=&quot;tiddlertags=='~~'&quot;; // 'untagged' tiddlers
		else
			terms[i]=&quot;/\\~&quot;+t+&quot;\\~/.test(tiddlertags)&quot;;
	}
	c=terms.join(&quot; &quot;);
	if (debug) { displayMessage(cmm.msg2.format([tagexpr])); displayMessage(cmm.msg3.format([c])); }

	// scan tiddlers for matches
	for (var t=0; t&lt;tids.length; t++) {
	 	// assemble tags from tiddler into string &quot;~tag1~tag2~tag3~&quot;
		var tiddlertags = &quot;~&quot;+tids[t].tags.join(&quot;~&quot;)+&quot;~&quot;;
		try { if(eval(c)) r.push(tids[t]); } // test tags
		catch(e) { // error in test
			displayMessage(cmm.msg2.format([tagexpr]));
			displayMessage(cmm.msg3.format([c]));
			displayMessage(e.toString());
			break; // skip remaining tiddlers
		}
	}
	if (debug) displayMessage(cmm.msg4.format([r.length,tagexpr]));
	return r;
}
//}}}
//{{{
config.macros.matchTags = {
	msg1: &quot;scanning %0 input tiddlers&quot;,
	msg2: &quot;looking for '%0'&quot;,
	msg3: &quot;using expression: '%0'&quot;,
	msg4: &quot;found %0 tiddlers matching '%1'&quot;,
	noMatch: &quot;no matching tiddlers&quot;,
	untaggedKeyword: &quot;-&quot;,
	untaggedLabel: &quot;no tags&quot;,
	untaggedPrompt: &quot;show tiddlers with no tags&quot;,
	defTiddler: &quot;MatchingTiddlers&quot;,
	defTags: &quot;&quot;,
	defFormat: &quot;[[%0]]&quot;,
	defSeparator: &quot;\n&quot;,
	reportHeading: &quot;Found %0 tiddlers tagged with: '{{{%1}}}'\n----\n&quot;,
	handler: function(place,macroName,params,wikifier,paramString,tiddler) {
		var mode=params[0]?params[0].toLowerCase():'';
		if (mode==&quot;inline&quot;)
			params.shift();
		if (mode==&quot;report&quot; || mode==&quot;panel&quot;) {
			params.shift();
			var target=params.shift()||this.defTiddler;
		}
		if (mode==&quot;popup&quot;) {
			params.shift();
			if (params[0]&amp;&amp;params[0].substr(0,6)==&quot;label:&quot;) var label=params.shift().substr(6);
			if (params[0]&amp;&amp;params[0].substr(0,7)==&quot;prompt:&quot;) var prompt=params.shift().substr(7);
		} else {
			var fmt=(params.shift()||this.defFormat).unescapeLineBreaks();
			var sep=(params.shift()||this.defSeparator).unescapeLineBreaks();
		}
		var sortBy=&quot;+title&quot;;
		if (params[0]&amp;&amp;params[0].substr(0,5)==&quot;sort:&quot;) sortBy=params.shift().substr(5);
		var expr = params.join(&quot; &quot;);
		if (mode!=&quot;panel&quot; &amp;&amp; (!expr||!expr.trim().length)) return;
		if (expr==this.untaggedKeyword)
			{ var label=this.untaggedLabel; var prompt=this.untaggedPrompt };
		switch (mode) {
			case &quot;popup&quot;: this.createPopup(place,label,expr,prompt,sortBy); break;
			case &quot;panel&quot;: this.createPanel(place,expr,fmt,sep,sortBy,target); break;
			case &quot;report&quot;: this.createReport(target,this.defTags,expr,fmt,sep,sortBy); break;
			case &quot;inline&quot;: default: this.createInline(place,expr,fmt,sep,sortBy); break;
		}
	},
	formatList: function(tids,fmt,sep) {
		var out=[];
		for (var i=0; i&lt;tids.length; i++) { var t=tids[i];
			var title=t.title;
			var who=t.modifier;
			var when=t.modified.toLocaleString();
			var text=t.text;
			var first=t.text.split(&quot;\n&quot;)[0];
			var desc=store.getTiddlerSlice(t.title,&quot;description&quot;);
			desc=desc||store.getTiddlerSlice(t.title,&quot;Description&quot;);
			desc=desc||store.getTiddlerText(t.title+&quot;##description&quot;);
			desc=desc||store.getTiddlerText(t.title+&quot;##Description&quot;);
			var tags=t.tags.length?'[['+t.tags.join(']] [[')+']]':'';
			out.push(fmt.format([title,who,when,text,first,desc,tags]));
		}
		return out.join(sep);
	},
	createInline: function(place,expr,fmt,sep,sortBy) {
		wikify(this.formatList(store.sortTiddlers(store.getMatchingTiddlers(expr),sortBy),fmt,sep),place);
	},
	createPopup: function(place,label,expr,prompt,sortBy) {
		var btn=createTiddlyButton(place,
			(label||expr).format([expr]),
			(prompt||config.views.wikified.tag.tooltip).format([expr]),
			function(ev){ return config.macros.matchTags.showPopup(this,ev||window.event); });
		btn.setAttribute(&quot;sortBy&quot;,sortBy);
		btn.setAttribute(&quot;expr&quot;,expr);
	},
	showPopup: function(here,ev) {
		var p=Popup.create(here); if (!p) return false;
		var tids=store.getMatchingTiddlers(here.getAttribute(&quot;expr&quot;));
		store.sortTiddlers(tids,here.getAttribute(&quot;sortBy&quot;));
		var list=[]; for (var t=0; t&lt;tids.length; t++) list.push(tids[t].title);
		if (!list.length) createTiddlyText(p,this.noMatch);
		else {
			var b=createTiddlyButton(createTiddlyElement(p,&quot;li&quot;),
				config.views.wikified.tag.openAllText,
				config.views.wikified.tag.openAllTooltip,
				function() {
					var list=this.getAttribute(&quot;list&quot;).readBracketedList();
					story.displayTiddlers(null,tids);
				});
			b.setAttribute(&quot;list&quot;,&quot;[[&quot;+list.join(&quot;]] [[&quot;)+&quot;]]&quot;);
			createTiddlyElement(p,&quot;hr&quot;);
		}
		var out=this.formatList(tids,&quot; &amp;nbsp;[[%0]]&amp;nbsp; &quot;,&quot;\n&quot;); wikify(out,p);
		Popup.show();
		ev.cancelBubble=true;
		if(ev.stopPropagation) ev.stopPropagation();
		return false;
	},
	createReport: function(target,tags,expr,fmt,sep,sortBy) {
		var tids=store.sortTiddlers(store.getMatchingTiddlers(expr),sortBy);
		if (!tids.length) { displayMessage('no matches for: '+expr); return false; }
		var msg=config.messages.overwriteWarning.format([target]);
		if (store.tiddlerExists(target) &amp;&amp; !confirm(msg)) return false;
		var out=this.reportHeading.format([tids.length,expr])
		out+=this.formatList(tids,fmt,sep);
		store.saveTiddler(target,target,out,config.options.txtUserName,new Date(),tags,{});
		story.closeTiddler(target); story.displayTiddler(null,target);
	},
	createPanel: function(place,expr,fmt,sep,sortBy,tid) {
		var s=createTiddlyElement(place,&quot;span&quot;); s.innerHTML=store.getTiddlerText(&quot;MatchTagsPlugin##html&quot;);
		var f=s.getElementsByTagName(&quot;form&quot;)[0];
		f.expr.value=expr; f.fmt.value=fmt; f.sep.value=sep.escapeLineBreaks();
		f.tid.value=tid; f.tags.value=this.defTags;
	}
};
//}}}
/***
//{{{
!html
&lt;form style='display:inline;white-space:nowrap'&gt;
&lt;input type='text'    name='expr' style='width:50%' title='tag expression'&gt;&lt;!--
--&gt;&lt;input type='text'    name='fmt'  style='width:10%' title='list item format'&gt;&lt;!--
--&gt;&lt;input type='text'    name='sep'  style='width:5%'  title='list item separator'&gt;&lt;!--
--&gt;&lt;input type='text'    name='tid'  style='width:12%' title='target tiddler title'&gt;&lt;!--
--&gt;&lt;input type='text'    name='tags' style='width:10%' title='target tiddler tags'&gt;&lt;!--
--&gt;&lt;input type='button'  name='go'   style='width:8%'  value='go' onclick=&quot;
	var expr=this.form.expr.value;
	if (!expr.length) { alert('Enter a boolean tag expression'); return false; }
	var fmt=this.form.fmt.value;
	if (!fmt.length) { alert('Enter the list item output format'); return false; }
	var sep=this.form.sep.value.unescapeLineBreaks();
	var tid=this.form.tid.value;
	if (!tid.length) { alert('Enter a target tiddler title'); return false; }
	var tags=this.form.tags.value;
	config.macros.matchTags.createReport(tid,tags,expr,fmt,sep,'title');
	return false;&quot;&gt;
&lt;/form&gt;
!end
//}}}
***/
//{{{
// SHADOW TIDDLER for displaying default panel input form
config.shadowTiddlers.MatchTags=&quot;&lt;&lt;matchTags panel&gt;&gt;&quot;;
//}}}
//{{{
// TWEAK core filterTiddlers() or config.filters['tag'] (in TW262+)
// to use getMatchingTiddlers instead getTaggedTiddlers
// for enhanced boolean matching in [tag[...]] syntax
var TW262=config.filters &amp;&amp; config.filters['tag']; // detect TW262+
var fname=TW262?&quot;config.filters['tag']&quot;:&quot;TiddlyWiki.prototype.filterTiddlers&quot;;
var code=eval(fname).toString().replace(/getTaggedTiddlers/g,'getMatchingTiddlers');
eval(fname+'='+code);
//}}}
//{{{
// REDEFINE core handler for enhanced boolean matching in tag:&quot;...&quot; paramifier
// use filterTiddlers() instead of getTaggedTiddlers() to get list of tiddlers.
config.paramifiers.tag = {
	onstart: function(v) {
		var tagged = store.filterTiddlers(&quot;[tag[&quot;+v+&quot;]]&quot;);
		story.displayTiddlers(null,tagged,null,false,null);
	}
};
//}}}</pre>
</div>
<div title="MatchTagsPluginInfo" modifier="ELSDesignStudios" created="200802290757" modified="201101232130" tags="pluginInfo" server.type="file" server.host="http://www.tiddlytools.com" server.page.revision="201101232130">
<pre>/***
|Name|MatchTagsPluginInfo|
|Source|http://www.TiddlyTools.com/#MatchTagsPlugin|
|Documentation|http://www.TiddlyTools.com/#MatchTagsPluginInfo|
|Version|2.0.5|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|documentation|
|Description|documentation for MatchTagsPlugin|
!!!!!Usage
&lt;&lt;&lt;
This plugin extends the {{{[tag[tagname]]}}} macro parameter syntax used by the TiddlyWiki core {{{&lt;&lt;list&gt;&gt;}}} macro so that, instead of a simple tagname value, you can specify a complex combination of tagname values using a //boolean expression// containing AND, OR, and NOT operators, enclosed in nested parentheses if needed.
{{{
&lt;&lt;list filter &quot;[tag[expression]]&quot;&gt;&gt;
}}}
In addition, the plugin defines a new macro, {{{&lt;&lt;matchTags ...&gt;&gt;}}} that can be used instead of the core {{{&lt;&lt;list&gt;&gt;}}} macro to output a list of matching tiddlers //using a custom 'item format' and 'separator'//.  You can also use this macro to create a command link that displays the matching tiddlers within a popup list, similar to the standard {{{&lt;&lt;tag tagName&gt;&gt;}}} macro, but matching a combination of tag values rather than a single tag value.
{{{
&lt;&lt;matchTags inline &quot;format&quot; &quot;separator&quot; sort:fieldname tag expression&gt;&gt;
&lt;&lt;matchTags popup &quot;label:...&quot; &quot;prompt:...&quot; sort:fieldname tag expression&gt;&gt;
&lt;&lt;matchTags report TiddlerName &quot;format&quot; &quot;separator&quot; sort:fieldname tag expression&gt;&gt;
&lt;&lt;matchTags panel  Tiddlername &quot;format&quot; &quot;separator&quot; sort:fieldname tag expression&gt;&gt;
}}}
where:
* ''inline'', ''report'', ''panel'', and ''popup''&lt;br&gt;are keywords that indicate the type of output that the macro should produce:
** ''inline'' //(default)// - displays a list of matching tiddlers embedded directly in tiddler content
** ''popup'' - embeds a command button that, when clicked, lists matching tiddlers in a ~TiddlyWiki popup display
** ''report'' - generates a list of matching tiddler in a separate [[MatchingTiddlers]] report tiddler
** ''panel'' - displays an interactive form for generating a [[MatchingTiddlers]] report
* ''format''&lt;br&gt;defines the wiki-syntax for rendering list items.  The following //substitution markers// can be used to insert tiddler-specific information for each matched tiddler:
** {{{%0}}} - title
** {{{%1}}} - modifier (author)
** {{{%2}}} - modified (date of last change)
** {{{%3}}} - text (all tiddler content)
** {{{%4}}} - firstline (tiddler content up to the first newline)
** {{{%5}}} - description (tiddler slice or section content named &quot;description&quot; or &quot;Description&quot;)
** {{{%6}}} - tags (space-separated, bracketed list)
* ''separator''&lt;br&gt;defines the wiki-syntax to use //between// each matching title (e.g., &quot;, &quot; creates a comma-separated list, while &quot;\n&quot; displays one tiddler per line).
* ''sort:fieldname'' (optional)&lt;br&gt;specifies the sort order for the resulting list of tiddlers.  You can specify any tiddler field name (standard or custom-defined).  Standard tiddler fieldnames include: //title, created, modified, modifier//.  If not specified, tiddlers are sorted by title.  You can prefix the fieldname with &quot;+&quot; or &quot;-&quot; to indicate ascending or descending order, respectively.
* ''tag expression''&lt;br&gt;the remaining parameter(s) are joined together to define the boolean expression to be matched.
When using the ''popup'' option, there are two additional (and optional) parameters you can specify:
* ''&quot;label:...&quot;''(optional)&lt;br&gt; indicates the text for the popup command link.  The default is to display the specified tag expression itself.
* ''&quot;prompt:...&quot;'' (optional)&lt;br&gt;indicates the mouseover 'tooltip' for the popup command link.
When using the ''report'' or ''panel'' option, an additional parameter may be provided:
* ''~TiddlerName''&lt;br&gt;specifies the target tiddler into which the output will be generated (default: [[MatchingTiddlers]])
Notes:
*A tag expression can use any combination of text operators: ''AND'', ''OR'', ''NOT'' (or their equivalent javascript operators: ''&amp;&amp;'', ''||'', ''!''), contained in nested parentheses as needed.
*Operators should be delimited by spaces or parentheses.
*Before matching, leading/trailing spaces are automatically trimmed and multiple spaces are reduced to single spaces.
*Tag values containing embedded spaces do //not// have to be enclosed in {{{[[...]]}}}.
*Tag values that contain boolean operators as ''literal text'' (e.g., {{{&quot;foo and bar&quot;}}} or {{{&quot;foo &amp;&amp; bar&quot;}}} cannot be used within a compound boolean expression, but //can// be matched if specified by themselves, without any other tag values or operators.
*To match tiddlers that are untagged, use &quot;-&quot; as a special tag value within the expression.
*You can match &quot;wildcard&quot; tags  by using //regular expression// (i.e., &quot;text pattern&quot;) syntax within a tag value, e.g. {{{[Tt]agvalue.*}}}
&lt;&lt;&lt;
!!!!!Examples:
&lt;&lt;&lt;
display a popup list:
{{{
&lt;&lt;matchTags popup sample OR (settings AND systemConfig)&gt;&gt;
}}}
&gt;&lt;&lt;matchTags popup sample OR (settings AND systemConfig)&gt;&gt;
display a popup list with custom label:
{{{
&lt;&lt;matchTags popup &quot;label:samples and settings&quot; sample OR (settings AND systemConfig)&gt;&gt;
}}}
&gt;&lt;&lt;matchTags popup &quot;label:samples and settings&quot; sample OR (settings AND systemConfig)&gt;&gt;
display a popup list of untagged tiddlers:
{{{
&lt;&lt;matchTags popup -&gt;&gt;
}}}
&gt;&lt;&lt;matchTags popup -&gt;&gt;
generate a report using interactive form control panel
{{{
&lt;&lt;matchTags panel &quot;MatchingTiddlers&quot; &quot;[[%0]]&quot; &quot;\n&quot; sample OR (settings AND systemConfig)&gt;&gt;
}}}
&gt;{{smallform{&lt;&lt;matchTags panel &quot;MatchingTiddlers&quot; &quot;[[%0]]&quot; &quot;\n&quot; sample OR (settings AND systemConfig)&gt;&gt;}}}
comma-separated list:
{{{
&lt;&lt;matchTags &quot;[[%0]]&quot; &quot;, &quot; sample OR (settings AND systemConfig)&gt;&gt;
}}}
&gt;&lt;&lt;matchTags &quot;[[%0]]&quot; &quot;, &quot; sample OR (settings AND systemConfig)&gt;&gt;
numbered list (sorted by modification date, most recent first):
{{{
&lt;&lt;matchTags &quot;#[[%0]] (%2)&lt;br&gt;^^%5^^&quot; &quot;\n&quot; sort:-modified sample OR (settings AND systemConfig)&gt;&gt;
}}}
&gt;&lt;&lt;matchTags &quot;#[[%0]] (%2)&lt;br&gt;^^%5^^&quot; &quot;\n&quot; sort:-modified sample OR (settings AND systemConfig)&gt;&gt;
bullet-item list (using the TiddlyWiki core {{{&lt;&lt;list filter ...&gt;&gt;}}} macro):
//(Note: when using the core {{{&lt;&lt;list&gt;&gt;}}} macro, you should always enclose the entire tag filter parameter within quotes)//
{{{
&lt;&lt;list filter &quot;[tag[sample OR (settings AND systemConfig)]]&quot;&gt;&gt;
}}}
&gt;&lt;&lt;list filter &quot;[tag[sample OR (settings AND systemConfig)]]&quot;&gt;&gt;
&lt;&lt;&lt;
!!!!!Revisions
&lt;&lt;&lt;
2011.01.22 2.0.5 fix core tweak for TW262+: adjust code in config.filters['tag'] instead of filterTiddlers()
2010.08.11 2.0.4 in getMatchingTiddlers(), fixed sorting for descending order (e.g, &quot;-created&quot;)
2010.03.02 2.0.3 added %6 format (tags)
2010.03.01 2.0.2 in formatList(), don't automatically put '[[' and ']]' around title (%0) in formatted output
2009.08.29 2.0.1 added support for {{{config.macros.matchTags.defTags}}} to auto-tag [[MatchingTiddlers]] output
2008.09.04 2.0.0 added &quot;report&quot; and &quot;panel&quot; options to generate formatted results and store in a tiddler.  Also, added config.macros.matchTags.formatList(place,fmt,sep) API to return formatted output for use with other plugins/scripts
2008.09.01 1.9.2 fixed return value from popup button handler so IE doesn't attempt to leave the page
2008.08.31 1.9.1 improved expression conversion handling to permit use of regular expressions for &quot;wildcard&quot; matching within tag values
2008.06.12 1.9.0 added support for formatted output of: title, who, when, text, firstline, description (slice or section)
2008.06.05 1.8.0 in getMatchingTiddlers(), added optional sortfield and tiddlers params to support use of alternative set of tiddlers instead of using current store content (provides filtering support for ImportTiddlersPlugin)
2008.06.04 1.7.1 in getMatchingTiddlers(), reworked conversion of expression for more robust parsing of whitespace, parentheses and javascript operators and allow use of &quot;-&quot; (untagged) //within// expressions
2008.05.19 1.7.0 in getMatchingTiddlers(), use reverseLookup() instead of forEachTiddler() to permit access to tiddlers included via [[IncludePlugin|http://tiddlywiki.abego-software.de/#IncludePlugin]]
2008.05.17 1.6.0 in getMatchingTiddlers(), rewrote expression conversion to handle tags with spaces tag values that are substrings of other tag values.
2008.05.16 1.5.0 added special case using &quot;-&quot; to find UNTAGGED tiddlers
2008.05.15 1.4.0 added &quot;popup&quot; output option
2008.05.14 1.3.4 instead of hijacking getTaggedTiddlers(), added tweak of filterTiddlers() prototype to replace getTaggedTiddlers() with getMatchingTiddler() so that core use of getTaggedTiddlers() does not perform boolean processing of tiddler titles such as [[To Be or not To Be]].  Also, improved &quot;filter error&quot; messages in getMatchingTiddlers() to report tag expression in addition to actual eval error.
2008.04.25 1.3.3 in getTaggedTiddlers(), fixed handling for &quot;not&quot; embedded within a tag
2008.04.21 1.3.2 in getTaggedTiddlers(), fixed handling for initial &quot;NOT&quot; and &quot;NOT(expr)&quot; syntax
2008.04.20 1.3.1 in getTaggedTiddlers(), corrected check for boolean expression to avoid excess processing of tags containing spaces.  Also, improved handling for non-existing tags that contain text of existing tags
2008.04.19 1.3.0 in filterTiddlers(), use getTaggedTiddlers() instead of matchTags(), and then hijack getTaggedTiddlers() to add matchTags() handling
2008.04.19 [*.*.*] plugin size reduction: moved documentation to [[MatchTagsPluginInfo]]
2008.03.25 1.2.0 added optional &quot;sort:fieldname&quot; parameter
2008.03.20 1.1.2 in handler(), replace 'encodeTiddlyLink' with explicit [[...]] brackets to ensure that one-word tiddler titles are properly rendered as TiddlyLinks
2008.02.29 1.1.1 in matchTags(), added handling to skip remaining tiddlers if expression has an error
2008.02.29 1.1.0 refactored to define store.matchTags() and extend store.filterTiddlers()
2008.02.28 1.0.0 initial release
&lt;&lt;&lt;</pre>
</div>
<div title="Math" modifier="Jonny Gerold" created="201008102027" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201008102027">
<pre>[[Project Euler]]</pre>
</div>
<div title="MptwBlack" modifier="MPTW" created="201004041423" modified="201009151231" tags="systemPalette">
<pre>Name: MptwBlack
Background: #000
Foreground: #fff
PrimaryPale: #333
PrimaryLight: #555
PrimaryMid: #888
PrimaryDark: #aaa
SecondaryPale: #111
SecondaryLight: #222
SecondaryMid: #555
SecondaryDark: #888
TertiaryPale: #222
TertiaryLight: #666
TertiaryMid: #888
TertiaryDark: #aaa
Error: #300

</pre>
</div>
<div title="MptwBlue" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemPalette">
<pre>Name: MptwBlue
Background: #fff
Foreground: #000
PrimaryPale: #cdf
PrimaryLight: #57c
PrimaryMid: #114
PrimaryDark: #012
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88

</pre>
</div>
<div title="MptwCollapsePlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>(function($){

merge(config.macros,{
	mptwCollapse: {
		handler: function(place,macroName,params) {
			createTiddlyButton(place, params[0] == '+' ? '\u25AD' : '\u25AC', 'collapse/uncollapse', function(){
				$(story.findContainingTiddler(place)).toggleClass('collapsed');
			});
		}
	}
});

/* this doesn't work unless you have a modified ViewTempate */
config.shadowTiddlers[&quot;MptwCollapsePluginStyles&quot;] = &quot;&quot;
	+&quot;.collapsed .uncollapsedView { display:none;       }&quot;
	+&quot;.collapsedView              { display:none;       }&quot;
	+&quot;.collapsed .collapsedView   { display:block;      }&quot;
	+&quot;.tiddler.collapsed          { padding-bottom:1em; }&quot;
	+&quot;.tiddler.collapsed .title   { font-size:100%;     }&quot;
;

store.addNotification(&quot;MptwCollapsePluginStyles&quot;,refreshStyles);

})(jQuery);
</pre>
</div>
<div title="MptwConfigPlugin" modifier="MPTW" created="201005122149" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|MptwConfigPlugin|
|Description:|Miscellaneous tweaks used by MPTW|
|Version:|1.0 ($Rev: 3646 $)|
|Date:|$Date: 2008-02-27 02:34:38 +1000 (Wed, 27 Feb 2008) $|
|Source:|http://mptw.tiddlyspot.com/#MptwConfigPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#MptwConfigPlugin|
!!Note: instead of editing this you should put overrides in MptwUserConfigPlugin
***/
//{{{
var originalReadOnly = readOnly;
var originalShowBackstage = showBackstage;

config.options.chkHttpReadOnly = false; 		// means web visitors can experiment with your site by clicking edit
readOnly = false;								// needed because the above doesn't work any more post 2.1 (??)
showBackstage = true;							// show backstage for same reason

config.options.chkInsertTabs = true;    		// tab inserts a tab when editing a tiddler
config.views.wikified.defaultText = &quot;&quot;;			// don't need message when a tiddler doesn't exist
config.views.editor.defaultText = &quot;&quot;;			// don't need message when creating a new tiddler 

config.options.chkSaveBackups = true;			// do save backups
config.options.txtBackupFolder = 'twbackup';	// put backups in a backups folder

config.options.chkAutoSave = (window.location.protocol == &quot;file:&quot;); // do autosave if we're in local file

config.mptwVersion = &quot;2.5.3&quot;;

config.macros.mptwVersion={handler:function(place){wikify(config.mptwVersion,place);}};

if (config.options.txtTheme == '')
	config.options.txtTheme = 'MptwTheme';

// add to default GettingStarted
config.shadowTiddlers.GettingStarted += &quot;\n\nSee also [[MPTW]].&quot;;

// add select theme and palette controls in default OptionsPanel
config.shadowTiddlers.OptionsPanel = config.shadowTiddlers.OptionsPanel.replace(/(\n\-\-\-\-\nAlso see \[\[AdvancedOptions\]\])/, &quot;{{select{&lt;&lt;selectTheme&gt;&gt;\n&lt;&lt;selectPalette&gt;&gt;}}}$1&quot;);

// these are used by ViewTemplate
config.mptwDateFormat = 'DD/MM/YY';
config.mptwJournalFormat = 'Journal DD/MM/YY';

//}}}
</pre>
</div>
<div title="MptwGreen" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemPalette">
<pre>Name: MptwGreen
Background: #fff
Foreground: #000
PrimaryPale: #9b9
PrimaryLight: #385
PrimaryMid: #031
PrimaryDark: #020
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88

</pre>
</div>
<div title="MptwRed" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemPalette">
<pre>Name: MptwRed
Background: #fff
Foreground: #000
PrimaryPale: #eaa
PrimaryLight: #c55
PrimaryMid: #711
PrimaryDark: #500
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88

</pre>
</div>
<div title="MptwRoundTheme" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemTheme">
<pre>|Name|MptwRounded|
|Description|Mptw Theme with some rounded corners (Firefox only)|
|ViewTemplate|MptwTheme##ViewTemplate|
|EditTemplate|MptwTheme##EditTemplate|
|PageTemplate|MptwTheme##PageTemplate|
|StyleSheet|##StyleSheet|

!StyleSheet
/*{{{*/

[[MptwTheme##StyleSheet]]

.tiddler,
.sliderPanel,
.button,
.tiddlyLink,
.tabContents
{ -moz-border-radius: 1em; }

.tab {
	-moz-border-radius-topleft: 0.5em;
	-moz-border-radius-topright: 0.5em;
}
#topMenu {
	-moz-border-radius-bottomleft: 2em;
	-moz-border-radius-bottomright: 2em;
}

/*}}}*/

</pre>
</div>
<div title="MptwSmoke" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemPalette">
<pre>Name: MptwSmoke
Background: #fff
Foreground: #000
PrimaryPale: #aaa
PrimaryLight: #777
PrimaryMid: #111
PrimaryDark: #000
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88

</pre>
</div>
<div title="MptwStandardTheme" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemTheme">
<pre>|Name|MptwStandard|
|Description|Mptw Theme with the default TiddlyWiki PageLayout and Styles|
|ViewTemplate|MptwTheme##ViewTemplate|
|EditTemplate|MptwTheme##EditTemplate|
</pre>
</div>
<div title="MptwTeal" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemPalette">
<pre>Name: MptwTeal
Background: #fff
Foreground: #000
PrimaryPale: #B5D1DF
PrimaryLight: #618FA9
PrimaryMid: #1a3844
PrimaryDark: #000
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #f8f8f8
TertiaryLight: #bbb
TertiaryMid: #999
TertiaryDark: #888
Error: #f88
</pre>
</div>
<div title="MptwTheme" modifier="MPTW" created="201005122154" modified="201009151231" tags="systemTheme">
<pre>|Name|MptwTheme|
|Description|Mptw Theme including custom PageLayout|
|PageTemplate|##PageTemplate|
|ViewTemplate|##ViewTemplate|
|EditTemplate|##EditTemplate|
|StyleSheet|##StyleSheet|

http://mptw.tiddlyspot.com/#MptwTheme ($Rev: 1829 $)

!PageTemplate
&lt;!--{{{--&gt;
&lt;div class='header' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'&gt;
	&lt;div class='headerShadow'&gt;
		&lt;span class='siteTitle' refresh='content' tiddler='SiteTitle'&gt;&lt;/span&gt;&amp;nbsp;
		&lt;span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'&gt;&lt;/span&gt;
	&lt;/div&gt;
	&lt;div class='headerForeground'&gt;
		&lt;span class='siteTitle' refresh='content' tiddler='SiteTitle'&gt;&lt;/span&gt;&amp;nbsp;
		&lt;span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'&gt;&lt;/span&gt;
	&lt;/div&gt;
&lt;/div&gt;
&lt;!-- horizontal MainMenu --&gt;
&lt;div id='topMenu' refresh='content' tiddler='MainMenu'&gt;&lt;/div&gt;
&lt;!-- original MainMenu menu --&gt;
&lt;!-- &lt;div id='mainMenu' refresh='content' tiddler='MainMenu'&gt;&lt;/div&gt; --&gt;
&lt;div id='sidebar'&gt;
	&lt;div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'&gt;&lt;/div&gt;
	&lt;div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div id='displayArea'&gt;
	&lt;div id='messageArea'&gt;&lt;/div&gt;
	&lt;div id='tiddlerDisplay'&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;!--}}}--&gt;

!ViewTemplate
&lt;!--{{{--&gt;
&lt;div class=&quot;uncollapsedView&quot;&gt;
[[MptwTheme##ViewTemplateToolbar]]

&lt;div class=&quot;tagglyTagged&quot; macro=&quot;tags&quot;&gt;&lt;/div&gt;

&lt;div class='titleContainer'&gt;
	&lt;span class='title' macro='view title'&gt;&lt;/span&gt;
	&lt;span macro=&quot;miniTag&quot;&gt;&lt;/span&gt;
&lt;/div&gt;

&lt;div class='subtitle'&gt;
	(updated &lt;span macro='view modified date {{config.mptwDateFormat?config.mptwDateFormat:&quot;MM/0DD/YY&quot;}}'&gt;&lt;/span&gt;
	by &lt;span macro='view modifier link'&gt;&lt;/span&gt;)
	&lt;!--
	(&lt;span macro='message views.wikified.createdPrompt'&gt;&lt;/span&gt;
	&lt;span macro='view created date {{config.mptwDateFormat?config.mptwDateFormat:&quot;MM/0DD/YY&quot;}}'&gt;&lt;/span&gt;)
	--&gt;
&lt;/div&gt;

&lt;div macro=&quot;showWhen tiddler.tags.containsAny(['css','html','pre','systemConfig']) &amp;&amp; !tiddler.text.match('{{'+'{')&quot;&gt;
	&lt;div class='viewer'&gt;&lt;pre macro='view text'&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div macro=&quot;else&quot;&gt;
	&lt;div class='viewer' macro='view text wikified'&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;div class=&quot;tagglyTagging&quot; macro=&quot;tagglyTagging&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;collapsedView&quot;&gt;
	&lt;span class='toolbar'&gt;
		&lt;span macro='toolbar closeTiddler'&gt;&lt;/span&gt;
		&lt;span macro='mptwCollapse +'&gt;&lt;/span&gt;
	&lt;/span&gt;
	&lt;span class='title' macro='view title'&gt;&lt;/span&gt;
&lt;/div&gt;

&lt;!--}}}--&gt;

!ViewTemplateToolbar
&lt;!--{{{--&gt;
&lt;div class='toolbar'&gt;
	&lt;span macro=&quot;showWhenTagged systemConfig&quot;&gt;
		&lt;span macro=&quot;toggleTag systemConfigDisable . '[[disable|systemConfigDisable]]'&quot;&gt;&lt;/span&gt;
	&lt;/span&gt;
	&lt;span macro=&quot;showWhenTagged systemTheme&quot;&gt;&lt;span macro=&quot;applyTheme&quot;&gt;&lt;/span&gt;&lt;/span&gt;
	&lt;span macro=&quot;showWhenTagged systemPalette&quot;&gt;&lt;span macro=&quot;applyPalette&quot;&gt;&lt;/span&gt;&lt;/span&gt;
	&lt;span macro=&quot;showWhen tiddler.tags.contains('css') || tiddler.title == 'StyleSheet'&quot;&gt;&lt;span macro=&quot;refreshAll&quot;&gt;&lt;/span&gt;&lt;/span&gt;
	&lt;span style=&quot;padding:1em;&quot;&gt;&lt;/span&gt;
	&lt;span macro='toolbar closeTiddler closeOthers +editTiddler deleteTiddler &gt; fields syncing permalink references jump'&gt;&lt;/span&gt; &lt;span macro='newHere label:&quot;new here&quot;'&gt;&lt;/span&gt;
	&lt;span macro='newJournalHere {{config.mptwJournalFormat?config.mptwJournalFormat:&quot;MM/0DD/YY&quot;}}'&gt;&lt;/span&gt;
	&lt;!--span macro='mptwCollapse -'&gt;&lt;/span--&gt;
&lt;/div&gt;
&lt;!--}}}--&gt;

!EditTemplate
&lt;!--{{{--&gt;
&lt;div class=&quot;toolbar&quot; macro=&quot;toolbar +saveTiddler saveCloseTiddler closeOthers -cancelTiddler cancelCloseTiddler deleteTiddler&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;title&quot; macro=&quot;view title&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;editLabel&quot;&gt;Title&lt;/div&gt;&lt;div class=&quot;editor&quot; macro=&quot;edit title&quot;&gt;&lt;/div&gt;
&lt;div macro='annotations'&gt;&lt;/div&gt;
&lt;div class=&quot;editLabel&quot;&gt;Content&lt;/div&gt;&lt;div class=&quot;editor&quot; macro=&quot;edit text&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;editLabel&quot;&gt;Tags&lt;/div&gt;&lt;div class=&quot;editor&quot; macro=&quot;edit tags&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;editorFooter&quot;&gt;&lt;span macro=&quot;message views.editor.tagPrompt&quot;&gt;&lt;/span&gt;&lt;span macro=&quot;tagChooser&quot;&gt;&lt;/span&gt;&lt;/div&gt;
&lt;!--}}}--&gt;

!StyleSheet
/*{{{*/

/* a contrasting background so I can see where one tiddler ends and the other begins */
body {
	background: [[ColorPalette::TertiaryLight]];
}

/* sexy colours and font for the header */
.headerForeground {
	color: [[ColorPalette::PrimaryPale]];
}
.headerShadow, .headerShadow a {
	color: [[ColorPalette::PrimaryMid]];
}

/* separate the top menu parts */
.headerForeground, .headerShadow {
	padding: 1em 1em 0;
}

.headerForeground, .headerShadow {
	font-family: 'Trebuchet MS', sans-serif;
	font-weight:bold;
}
.headerForeground .siteSubtitle {
	color: [[ColorPalette::PrimaryLight]];
}
.headerShadow .siteSubtitle {
	color: [[ColorPalette::PrimaryMid]];
}

/* make shadow go and down right instead of up and left */
.headerShadow {
	left: 1px;
	top: 1px;
}

/* prefer monospace for editing */
.editor textarea, .editor input {
	font-family: 'Consolas', monospace;
	background-color:[[ColorPalette::TertiaryPale]];
}


/* sexy tiddler titles */
.title {
	font-size: 250%;
	color: [[ColorPalette::PrimaryLight]];
	font-family: 'Trebuchet MS', sans-serif;
}

/* more subtle tiddler subtitle */
.subtitle {
	padding:0px;
	margin:0px;
	padding-left:1em;
	font-size: 90%;
	color: [[ColorPalette::TertiaryMid]];
}
.subtitle .tiddlyLink {
	color: [[ColorPalette::TertiaryMid]];
}

/* a little bit of extra whitespace */
.viewer {
	padding-bottom:3px;
}

/* don't want any background color for headings */
h1,h2,h3,h4,h5,h6 {
	background-color: transparent;
	color: [[ColorPalette::Foreground]];
}

/* give tiddlers 3d style border and explicit background */
.tiddler {
	background: [[ColorPalette::Background]];
	border-right: 2px [[ColorPalette::TertiaryMid]] solid;
	border-bottom: 2px [[ColorPalette::TertiaryMid]] solid;
	margin-bottom: 1em;
	padding:1em 2em 2em 1.5em;
}

/* make options slider look nicer */
#sidebarOptions .sliderPanel {
	border:solid 1px [[ColorPalette::PrimaryLight]];
}

/* the borders look wrong with the body background */
#sidebar .button {
	border-style: none;
}

/* this means you can put line breaks in SidebarOptions for readability */
#sidebarOptions br {
	display:none;
}
/* undo the above in OptionsPanel */
#sidebarOptions .sliderPanel br {
	display:inline;
}

/* horizontal main menu stuff */
#displayArea {
	margin: 1em 15.7em 0em 1em; /* use the freed up space */
}
#topMenu br {
	display: none;
}
#topMenu {
	background: [[ColorPalette::PrimaryMid]];
	color:[[ColorPalette::PrimaryPale]];
}
#topMenu {
	padding:2px;
}
#topMenu .button, #topMenu .tiddlyLink, #topMenu a {
	margin-left: 0.5em;
	margin-right: 0.5em;
	padding-left: 3px;
	padding-right: 3px;
	color: [[ColorPalette::PrimaryPale]];
	font-size: 115%;
}
#topMenu .button:hover, #topMenu .tiddlyLink:hover {
	background: [[ColorPalette::PrimaryDark]];
}

/* make 2.2 act like 2.1 with the invisible buttons */
.toolbar {
	visibility:hidden;
}
.selected .toolbar {
	visibility:visible;
}

/* experimental. this is a little borked in IE7 with the button 
 * borders but worth it I think for the extra screen realestate */
.toolbar { float:right; }

/* fix for TaggerPlugin. from sb56637. improved by FND */
.popup li .tagger a {
   display:inline;
}

/* makes theme selector look a little better */
#sidebarOptions .sliderPanel .select .button {
  padding:0.5em;
  display:block;
}
#sidebarOptions .sliderPanel .select br {
	display:none;
}

/* make it print a little cleaner */
@media print {
	#topMenu {
		display: none ! important;
	}
	/* not sure if we need all the importants */
	.tiddler {
		border-style: none ! important;
		margin:0px ! important;
		padding:0px ! important;
		padding-bottom:2em ! important;
	}
	.tagglyTagging .button, .tagglyTagging .hidebutton {
		display: none ! important;
	}
	.headerShadow {
		visibility: hidden ! important;
	}
	.tagglyTagged .quickopentag, .tagged .quickopentag {
		border-style: none ! important;
	}
	.quickopentag a.button, .miniTag {
		display: none ! important;
	}
}

/* get user styles specified in StyleSheet */
[[StyleSheet]]

/*}}}*/

</pre>
</div>
<div title="MptwTrimTheme" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemTheme">
<pre>|Name|MptwTrim|
|Description|Mptw Theme with a reduced header to increase useful space|
|ViewTemplate|MptwTheme##ViewTemplate|
|EditTemplate|MptwTheme##EditTemplate|
|StyleSheet|MptwTheme##StyleSheet|
|PageTemplate|##PageTemplate|

!PageTemplate
&lt;!--{{{--&gt;

&lt;!-- horizontal MainMenu --&gt;
&lt;div id='topMenu' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'&gt;
&lt;span refresh='content' tiddler='SiteTitle' style=&quot;padding-left:1em;font-weight:bold;&quot;&gt;&lt;/span&gt;:
&lt;span refresh='content' tiddler='MainMenu'&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div id='sidebar'&gt;
	&lt;div id='sidebarOptions'&gt;
		&lt;div refresh='content' tiddler='SideBarOptions'&gt;&lt;/div&gt;
		&lt;div style=&quot;margin-left:0.1em;&quot;
			macro='slider chkTabSliderPanel SideBarTabs {{&quot;tabs \u00bb&quot;}} &quot;Show Timeline, All, Tags, etc&quot;'&gt;&lt;/div&gt;
	&lt;/div&gt;
&lt;/div&gt;
&lt;div id='displayArea'&gt;
	&lt;div id='messageArea'&gt;&lt;/div&gt;
	&lt;div id='tiddlerDisplay'&gt;&lt;/div&gt;
&lt;/div&gt;

</pre>
</div>
<div title="MptwUpgradeURL" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemServer">
<pre>For upgrading. See [[ImportTiddlers]].
URL: http://mptw.tiddlyspot.com/upgrade.html
</pre>
</div>
<div title="MptwUserConfigPlugin" modifier="StephenWilliams" created="201004041418" modified="201103090715" tags="systemConfig" changecount="1">
<pre>/***
|Description:|A place to put your config tweaks so they aren't overwritten when you upgrade MPTW|
See http://www.tiddlywiki.org/wiki/Configuration_Options for other options you can set. In some cases where there are clashes with other plugins it might help to rename this to zzMptwUserConfigPlugin so it gets executed last.
***/
//{{{

// example: set your preferred date format
//config.mptwDateFormat = 'MM/0DD/YY';
//config.mptwJournalFormat = 'Journal MM/0DD/YY';

// example: set the theme you want to start with
config.options.txtTheme = 'MptwRoundTheme';

// example: switch off autosave, switch on backups and set a backup folder
//config.options.chkSaveBackups = true;
//config.options.chkAutoSave = false;
//config.options.txtBackupFolder = 'backups';

// uncomment to disable 'new means new' functionality for the new journal macro
//config.newMeansNewForJournalsToo = false;

//}}}
</pre>
</div>
<div title="NewHerePlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|NewHerePlugin|
|Description:|Creates the new here and new journal macros|
|Version:|3.0 ($Rev: 3861 $)|
|Date:|$Date: 2008-03-08 10:53:09 +1000 (Sat, 08 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#NewHerePlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License|http://mptw.tiddlyspot.com/#TheBSDLicense|
***/
//{{{
merge(config.macros, {
	newHere: {
		handler: function(place,macroName,params,wikifier,paramString,tiddler) {
			wikify(&quot;&lt;&lt;newTiddler &quot;+paramString+&quot; tag:[[&quot;+tiddler.title+&quot;]]&gt;&gt;&quot;,place,null,tiddler);
		}
	},
	newJournalHere: {
		handler: function(place,macroName,params,wikifier,paramString,tiddler) {
			wikify(&quot;&lt;&lt;newJournal &quot;+paramString+&quot; tag:[[&quot;+tiddler.title+&quot;]]&gt;&gt;&quot;,place,null,tiddler);
		}
	}
});

//}}}

</pre>
</div>
<div title="NewMeansNewPlugin" modifier="MPTW" created="201004041422" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|NewMeansNewPlugin|
|Description:|If 'New Tiddler' already exists then create 'New Tiddler (1)' and so on|
|Version:|1.1.1 ($Rev: 2263 $)|
|Date:|$Date: 2007-06-13 04:22:32 +1000 (Wed, 13 Jun 2007) $|
|Source:|http://mptw.tiddlyspot.com/empty.html#NewMeansNewPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Note: I think this should be in the core
***/
//{{{

// change this or set config.newMeansNewForJournalsToo it in MptwUuserConfigPlugin
if (config.newMeansNewForJournalsToo == undefined) config.newMeansNewForJournalsToo = true;

String.prototype.getNextFreeName = function() {
	numberRegExp = / \(([0-9]+)\)$/;
	var match = numberRegExp.exec(this);
	if (match) {
	var num = parseInt(match[1]) + 1;
		return this.replace(numberRegExp,&quot; (&quot;+num+&quot;)&quot;);
	}
	else {
		return this + &quot; (1)&quot;;
	}
}

config.macros.newTiddler.checkForUnsaved = function(newName) {
	var r = false;
	story.forEachTiddler(function(title,element) {
		if (title == newName)
			r = true;
	});
	return r;
}

config.macros.newTiddler.getName = function(newName) {
	while (store.getTiddler(newName) || config.macros.newTiddler.checkForUnsaved(newName))
		newName = newName.getNextFreeName();
	return newName;
}


config.macros.newTiddler.onClickNewTiddler = function()
{
	var title = this.getAttribute(&quot;newTitle&quot;);
	if(this.getAttribute(&quot;isJournal&quot;) == &quot;true&quot;) {
		title = new Date().formatString(title.trim());
	}

	// ---- these three lines should be the only difference between this and the core onClickNewTiddler
	if (config.newMeansNewForJournalsToo || this.getAttribute(&quot;isJournal&quot;) != &quot;true&quot;)
		title = config.macros.newTiddler.getName(title);

	var params = this.getAttribute(&quot;params&quot;);
	var tags = params ? params.split(&quot;|&quot;) : [];
	var focus = this.getAttribute(&quot;newFocus&quot;);
	var template = this.getAttribute(&quot;newTemplate&quot;);
	var customFields = this.getAttribute(&quot;customFields&quot;);
	if(!customFields &amp;&amp; !store.isShadowTiddler(title))
		customFields = String.encodeHashMap(config.defaultCustomFields);
	story.displayTiddler(null,title,template,false,null,null);
	var tiddlerElem = story.getTiddler(title);
	if(customFields)
		story.addCustomFields(tiddlerElem,customFields);
	var text = this.getAttribute(&quot;newText&quot;);
	if(typeof text == &quot;string&quot;)
		story.getTiddlerField(title,&quot;text&quot;).value = text.format([title]);
	for(var t=0;t&lt;tags.length;t++)
		story.setTiddlerTag(title,tags[t],+1);
	story.focusTiddler(title,focus);
	return false;
};

//}}}

</pre>
</div>
<div title="OpenTaggedTiddlers" modifier="StephenWilliams" created="200611180748" modified="201103090805" tags="systemConfig systemConfigDisable" server.type="file" server.host="http://www.tiddlytools.com" server.page.revision="200909261537" changecount="4">
<pre>/%
!info
|Name|OpenTaggedTiddlers|
|Source|http://www.TiddlyTools.com/#OpenTaggedTiddlers|
|Version|2.0.0|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|transclusion|
|Description|create a link to open a set of tagged tiddlers with a single click|
Usage:
&lt;&lt;&lt;
{{{
&lt;&lt;tiddler OpenTaggedTiddlers with: label tagToMatch sortBy reverse close limit&gt;&gt;
}}}
*''label''&lt;br&gt;is the text of the link
*''tagToMatch''&lt;br&gt;is a single tag value to be matched.  Note: when MatchTagsPlugin is installed, you can also use a boolean tag expression, enclosed in &quot;...&quot;
*''sortBy'' (optional)&lt;br&gt;a tiddler fieldname, (default=&quot;title&quot;, use &quot;modified&quot; or &quot;created&quot; for tiddler dates)
*''reverse'' (optional)&lt;br&gt;display order for the tiddlers (i.e., descending vs. ascending)
*''close'' (optional)&lt;br&gt;closes all open tiddlers before opening the tagged tiddlers
*''limit'' (optional)&lt;br&gt;maximum number of tiddlers to be opened
Note: use &quot;&quot; as placeholders when omitting optional parameters
&lt;&lt;&lt;
Example
&lt;&lt;&lt;
{{{&lt;&lt;tiddler OpenTaggedTiddlers##show with: &quot;click me...&quot; sample title reverse &quot;&quot; 3&gt;&gt;}}}
&lt;&lt;tiddler OpenTaggedTiddlers##show with: &quot;click me...&quot; sample title reverse &quot;&quot; 3&gt;&gt;
&lt;&lt;&lt;
!end
!show
&lt;html&gt;&lt;nowiki&gt;&lt;a href='javascript:;' onclick=&quot;
	var list=[];
	var match='$2';
	var sortBy='$3'; if ((sortBy=='$'+'3')||(sortBy=='')) sortBy='title';
	var filter='[tag[%0]][sort[%1]]'.format([match,sortBy]);
	var tids=store.filterTiddlers(filter);
	if ('$4'=='reverse') tids=tids.reverse();
	if ('$5'=='close') story.closeAllTiddlers();
	var limit=('$6'!='$'+'6')?parseInt('$6'):tids.length;
	for (var t=0;t&lt;tids.length &amp;&amp; t&lt;limit;t++) list.push(tids[t].title);
	if (confirm('Show %0 tiddlers tagged with \x27%1\x27?'.format([tids.length,match]))) {
		var here=story.findContainingTiddler(place);
		story.displayTiddlers(here,list);
		if (here &amp;&amp; list.length) { // scroll to top of newly displayed tiddlers
			var cmd='window.scrollTo(0,'+(here.offsetTop+here.offsetHeight)+')';
			var delay=config.options.chkAnimate?config.animDuration+100:0;
			setTimeout(cmd,delay);
		}
	}
	return false;
&quot;&gt;$1&lt;/a&gt;&lt;/html&gt;
!end
%/&lt;&lt;tiddler {{var src='OpenTaggedTiddlers'; src+(tiddler&amp;&amp;tiddler.title==src?'##info':'##show')}}
	with: [[$1]] [[$2]] [[$3]] [[$4]] [[$5]] [[$6]]&gt;&gt;</pre>
</div>
<div title="OptimaLogic" modifier="StephenWilliams" created="201103090010" modified="201103100019" tags="Corporate sdw" changecount="13">
<pre>OptimaLogic, Inc. is a lean R&amp;D consulting organization located in Silicon Valley that provides highly technical mobile, desktop, and server related consulting in a variety of areas.  These include:
* mobile &amp; service architecture/design, 
* Android &amp; NDK / iOS / WebOS,
* web services, 
* crypto / security,
* scalable server applications,
* database / storage,
* machine vision, and
* cutting edge UI.
Recent clients include technical startups, multi-national corporations, government agencies, and academia.  With access to a wide range of resources, OptimaLogic can quickly find the optimal solution for your most challenging projects.  We have a particular interest in early stage startups and high-profile, important projects.

Look for the [[Concise Coding]] book soon.

[[Stephen Williams|mailto:sdw@lig.net]] leads and runs OptimaLogic.  [[Resume|http://sdw.st/gres]]  [[LinkedIn|http://sdw.st/in]]</pre>
</div>
<div title="PageTemplate" modifier="StephenWilliams" created="201103080642" modified="201103080651" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" changecount="3">
<pre>&lt;!--{{{--&gt;
&lt;div class='header' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'&gt;
&lt;div class='headerShadow'&gt;
&lt;span class='siteTitle' refresh='content' tiddler='SiteTitle'&gt;&lt;/span&gt;&amp;nbsp;
&lt;span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;div class='headerForeground'&gt;
&lt;span class='siteTitle' refresh='content' tiddler='SiteTitle'&gt;&lt;/span&gt;&amp;nbsp;
&lt;span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div id='mainMenu' refresh='content' tiddler='MainMenu'&gt;&lt;/div&gt;
&lt;div id='sidebar'&gt;
&lt;div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'&gt;&lt;/div&gt;
&lt;div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div id='displayArea'&gt;
&lt;div id='messageArea'&gt;&lt;/div&gt;
&lt;!-- &lt;div id='tiddlersBar' refresh='none' ondblclick='config.macros.tiddlersBar.onTiddlersBarAction(event)'&gt;&lt;/div&gt; --&gt;
&lt;div id='tiddlerDisplay'&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;!--}}}--&gt;</pre>
</div>
<div title="PrettyDatesPlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|PrettyDatesPlugin|
|Description:|Provides a new date format ('pppp') that displays times such as '2 days ago'|
|Version:|1.0 ($Rev: 3646 $)|
|Date:|$Date: 2008-02-27 02:34:38 +1000 (Wed, 27 Feb 2008) $|
|Source:|http://mptw.tiddlyspot.com/#PrettyDatesPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Notes
* If you want to you can rename this plugin. :) Some suggestions: LastUpdatedPlugin, RelativeDatesPlugin, SmartDatesPlugin, SexyDatesPlugin.
* Inspired by http://ejohn.org/files/pretty.js
***/
//{{{
Date.prototype.prettyDate = function() {
	var diff = (((new Date()).getTime() - this.getTime()) / 1000);
	var day_diff = Math.floor(diff / 86400);

	if (isNaN(day_diff))      return &quot;&quot;;
	else if (diff &lt; 0)        return &quot;in the future&quot;;
	else if (diff &lt; 60)       return &quot;just now&quot;;
	else if (diff &lt; 120)      return &quot;1 minute ago&quot;;
	else if (diff &lt; 3600)     return Math.floor(diff/60) + &quot; minutes ago&quot;;
	else if (diff &lt; 7200)     return &quot;1 hour ago&quot;;
	else if (diff &lt; 86400)    return Math.floor(diff/3600) + &quot; hours ago&quot;;
	else if (day_diff == 1)   return &quot;Yesterday&quot;;
	else if (day_diff &lt; 7)    return day_diff + &quot; days ago&quot;;
	else if (day_diff &lt; 14)   return  &quot;a week ago&quot;;
	else if (day_diff &lt; 31)   return Math.ceil(day_diff/7) + &quot; weeks ago&quot;;
	else if (day_diff &lt; 62)   return &quot;a month ago&quot;;
	else if (day_diff &lt; 365)  return &quot;about &quot; + Math.ceil(day_diff/31) + &quot; months ago&quot;;
	else if (day_diff &lt; 730)  return &quot;a year ago&quot;;
	else                      return Math.ceil(day_diff/365) + &quot; years ago&quot;;
}

Date.prototype.formatString_orig_mptw = Date.prototype.formatString;

Date.prototype.formatString = function(template) {
	return this.formatString_orig_mptw(template).replace(/pppp/,this.prettyDate());
}

// for MPTW. otherwise edit your ViewTemplate as required.
// config.mptwDateFormat = 'pppp (DD/MM/YY)'; 
config.mptwDateFormat = 'pppp'; 

//}}}

</pre>
</div>
<div title="Pro Git" modifier="Jonny Gerold" created="201008102046" modified="201008102101" tags="Books" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201008102101">
<pre>* [[1 - Getting Started|PG_1 - Getting Started]]
* [[2 - Git Basics|PG_2 - Git Basics]]
* [[3 - Git Branching|PG_3 - Git Branching]]</pre>
</div>
<div title="Programming" modifier="Jonny Gerold" created="201008102249" modified="201012140353" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201012140353">
<pre>* [[AWK/SED]]
* [[C++]]
* [[C]]
* [[LISP]]
* [[Octave]]
* [[PHP|PHP.net]]</pre>
</div>
<div title="QuickOpenTagPlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|QuickOpenTagPlugin|
|Description:|Changes tag links to make it easier to open tags as tiddlers|
|Version:|3.0.1 ($Rev: 3861 $)|
|Date:|$Date: 2008-03-08 10:53:09 +1000 (Sat, 08 Mar 2008) $|
|Source:|http://mptw.tiddlyspot.com/#QuickOpenTagPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
***/
//{{{
config.quickOpenTag = {

	dropdownChar: (document.all ? &quot;\u25bc&quot; : &quot;\u25be&quot;), // the little one doesn't work in IE?

	createTagButton: function(place,tag,excludeTiddler) {
		// little hack so we can do this: &lt;&lt;tag PrettyTagName|RealTagName&gt;&gt;
		var splitTag = tag.split(&quot;|&quot;);
		var pretty = tag;
		if (splitTag.length == 2) {
			tag = splitTag[1];
			pretty = splitTag[0];
		}
		
		var sp = createTiddlyElement(place,&quot;span&quot;,null,&quot;quickopentag&quot;);
		createTiddlyText(createTiddlyLink(sp,tag,false),pretty);
		
		var theTag = createTiddlyButton(sp,config.quickOpenTag.dropdownChar,
                        config.views.wikified.tag.tooltip.format([tag]),onClickTag);
		theTag.setAttribute(&quot;tag&quot;,tag);
		if (excludeTiddler)
			theTag.setAttribute(&quot;tiddler&quot;,excludeTiddler);
    		return(theTag);
	},

	miniTagHandler: function(place,macroName,params,wikifier,paramString,tiddler) {
		var tagged = store.getTaggedTiddlers(tiddler.title);
		if (tagged.length &gt; 0) {
			var theTag = createTiddlyButton(place,config.quickOpenTag.dropdownChar,
                        	config.views.wikified.tag.tooltip.format([tiddler.title]),onClickTag);
			theTag.setAttribute(&quot;tag&quot;,tiddler.title);
			theTag.className = &quot;miniTag&quot;;
		}
	},

	allTagsHandler: function(place,macroName,params) {
		var tags = store.getTags(params[0]);
		var filter = params[1]; // new feature
		var ul = createTiddlyElement(place,&quot;ul&quot;);
		if(tags.length == 0)
			createTiddlyElement(ul,&quot;li&quot;,null,&quot;listTitle&quot;,this.noTags);
		for(var t=0; t&lt;tags.length; t++) {
			var title = tags[t][0];
			if (!filter || (title.match(new RegExp('^'+filter)))) {
				var info = getTiddlyLinkInfo(title);
				var theListItem =createTiddlyElement(ul,&quot;li&quot;);
				var theLink = createTiddlyLink(theListItem,tags[t][0],true);
				var theCount = &quot; (&quot; + tags[t][1] + &quot;)&quot;;
				theLink.appendChild(document.createTextNode(theCount));
				var theDropDownBtn = createTiddlyButton(theListItem,&quot; &quot; +
					config.quickOpenTag.dropdownChar,this.tooltip.format([tags[t][0]]),onClickTag);
				theDropDownBtn.setAttribute(&quot;tag&quot;,tags[t][0]);
			}
		}
	},

	// todo fix these up a bit
	styles: [
&quot;/*{{{*/&quot;,
&quot;/* created by QuickOpenTagPlugin */&quot;,
&quot;.tagglyTagged .quickopentag, .tagged .quickopentag &quot;,
&quot;	{ margin-right:1.2em; border:1px solid #eee; padding:2px; padding-right:0px; padding-left:1px; }&quot;,
&quot;.quickopentag .tiddlyLink { padding:2px; padding-left:3px; }&quot;,
&quot;.quickopentag a.button { padding:1px; padding-left:2px; padding-right:2px;}&quot;,
&quot;/* extra specificity to make it work right */&quot;,
&quot;#displayArea .viewer .quickopentag a.button, &quot;,
&quot;#displayArea .viewer .quickopentag a.tiddyLink, &quot;,
&quot;#mainMenu .quickopentag a.tiddyLink, &quot;,
&quot;#mainMenu .quickopentag a.tiddyLink &quot;,
&quot;	{ border:0px solid black; }&quot;,
&quot;#displayArea .viewer .quickopentag a.button, &quot;,
&quot;#mainMenu .quickopentag a.button &quot;,
&quot;	{ margin-left:0px; padding-left:2px; }&quot;,
&quot;#displayArea .viewer .quickopentag a.tiddlyLink, &quot;,
&quot;#mainMenu .quickopentag a.tiddlyLink &quot;,
&quot;	{ margin-right:0px; padding-right:0px; padding-left:0px; margin-left:0px; }&quot;,
&quot;a.miniTag {font-size:150%;} &quot;,
&quot;#mainMenu .quickopentag a.button &quot;,
&quot;	/* looks better in right justified main menus */&quot;,
&quot;	{ margin-left:0px; padding-left:2px; margin-right:0px; padding-right:0px; }&quot;, 
&quot;#topMenu .quickopentag { padding:0px; margin:0px; border:0px; }&quot;,
&quot;#topMenu .quickopentag .tiddlyLink { padding-right:1px; margin-right:0px; }&quot;,
&quot;#topMenu .quickopentag .button { padding-left:1px; margin-left:0px; border:0px; }&quot;,
&quot;/*}}}*/&quot;,
		&quot;&quot;].join(&quot;\n&quot;),

	init: function() {
		// we fully replace these builtins. can't hijack them easily
		window.createTagButton = this.createTagButton;
		config.macros.allTags.handler = this.allTagsHandler;
		config.macros.miniTag = { handler: this.miniTagHandler };
		config.shadowTiddlers[&quot;QuickOpenTagStyles&quot;] = this.styles;
		store.addNotification(&quot;QuickOpenTagStyles&quot;,refreshStyles);
	}
}

config.quickOpenTag.init();

//}}}

</pre>
</div>
<div title="RenameTagsPlugin" modifier="MPTW" created="201008231244" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|RenameTagsPlugin|
|Description:|Allows you to easily rename or delete tags across multiple tiddlers|
|Version:|3.0 ($Rev: 5501 $)|
|Date:|$Date: 2008-06-10 23:11:55 +1000 (Tue, 10 Jun 2008) $|
|Source:|http://mptw.tiddlyspot.com/#RenameTagsPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License|http://mptw.tiddlyspot.com/#TheBSDLicense|
Rename a tag and you will be prompted to rename it in all its tagged tiddlers.
***/
//{{{
config.renameTags = {

	prompts: {
		rename: &quot;Rename the tag '%0' to '%1' in %2 tidder%3?&quot;,
		remove: &quot;Remove the tag '%0' from %1 tidder%2?&quot;
	},

	removeTag: function(tag,tiddlers) {
		store.suspendNotifications();
		for (var i=0;i&lt;tiddlers.length;i++) {
			store.setTiddlerTag(tiddlers[i].title,false,tag);
		}
		store.resumeNotifications();
		store.notifyAll();
	},

	renameTag: function(oldTag,newTag,tiddlers) {
		store.suspendNotifications();
		for (var i=0;i&lt;tiddlers.length;i++) {
			store.setTiddlerTag(tiddlers[i].title,false,oldTag); // remove old
			store.setTiddlerTag(tiddlers[i].title,true,newTag);  // add new
		}
		store.resumeNotifications();
		store.notifyAll();
	},

	storeMethods: {

		saveTiddler_orig_renameTags: TiddlyWiki.prototype.saveTiddler,

		saveTiddler: function(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created,creator) {
			if (title != newTitle) {
				var tagged = this.getTaggedTiddlers(title);
				if (tagged.length &gt; 0) {
					// then we are renaming a tag
					if (confirm(config.renameTags.prompts.rename.format([title,newTitle,tagged.length,tagged.length&gt;1?&quot;s&quot;:&quot;&quot;])))
						config.renameTags.renameTag(title,newTitle,tagged);

					if (!this.tiddlerExists(title) &amp;&amp; newBody == &quot;&quot;)
						// dont create unwanted tiddler
						return null;
				}
			}
			return this.saveTiddler_orig_renameTags(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created,creator);
		},

		removeTiddler_orig_renameTags: TiddlyWiki.prototype.removeTiddler,

		removeTiddler: function(title) {
			var tagged = this.getTaggedTiddlers(title);
			if (tagged.length &gt; 0)
				if (confirm(config.renameTags.prompts.remove.format([title,tagged.length,tagged.length&gt;1?&quot;s&quot;:&quot;&quot;])))
					config.renameTags.removeTag(title,tagged);
			return this.removeTiddler_orig_renameTags(title);
		}

	},

	init: function() {
		merge(TiddlyWiki.prototype,this.storeMethods);
	}
}

config.renameTags.init();

//}}}

</pre>
</div>
<div title="SaveCloseTiddlerPlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|SaveCloseTiddlerPlugin|
|Description:|Provides two extra toolbar commands, saveCloseTiddler and cancelCloseTiddler|
|Version:|3.0 ($Rev: 5502 $)|
|Date:|$Date: 2008-06-10 23:31:39 +1000 (Tue, 10 Jun 2008) $|
|Source:|http://mptw.tiddlyspot.com/#SaveCloseTiddlerPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
To use these you must add them to the tool bar in your EditTemplate
***/
//{{{
merge(config.commands,{

	saveCloseTiddler: {
		text: 'done/close',
		tooltip: 'Save changes to this tiddler and close it',
		handler: function(ev,src,title) {
			var closeTitle = title;
			var newTitle = story.saveTiddler(title,ev.shiftKey);
			if (newTitle)
				closeTitle = newTitle;
			return config.commands.closeTiddler.handler(ev,src,closeTitle);
		}
	},

	cancelCloseTiddler: {
		text: 'cancel/close',
		tooltip: 'Undo changes to this tiddler and close it',
		handler: function(ev,src,title) {
			// the same as closeTiddler now actually
			return config.commands.closeTiddler.handler(ev,src,title);
		}
	}

});

//}}}

</pre>
</div>
<div title="SelectThemePlugin" modifier="MPTW" created="201004041422" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|SelectThemePlugin|
|Description:|Lets you easily switch theme and palette|
|Version:|1.0.1 ($Rev: 3646 $)|
|Date:|$Date: 2008-02-27 02:34:38 +1000 (Wed, 27 Feb 2008) $|
|Source:|http://mptw.tiddlyspot.com/#SelectThemePlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!Notes
* Borrows largely from ThemeSwitcherPlugin by Martin Budden http://www.martinswiki.com/#ThemeSwitcherPlugin
* Theme is cookie based. But set a default by setting config.options.txtTheme in MptwConfigPlugin (for example)
* Palette is not cookie based. It actually overwrites your ColorPalette tiddler when you select a palette, so beware. 
!Usage
* {{{&lt;&lt;selectTheme&gt;&gt;}}} makes a dropdown selector
* {{{&lt;&lt;selectPalette&gt;&gt;}}} makes a dropdown selector
* {{{&lt;&lt;applyTheme&gt;&gt;}}} applies the current tiddler as a theme
* {{{&lt;&lt;applyPalette&gt;&gt;}}} applies the current tiddler as a palette
* {{{&lt;&lt;applyTheme TiddlerName&gt;&gt;}}} applies TiddlerName as a theme
* {{{&lt;&lt;applyPalette TiddlerName&gt;&gt;}}} applies TiddlerName as a palette
***/
//{{{

config.macros.selectTheme = {
	label: {
		selectTheme:&quot;select theme&quot;,
		selectPalette:&quot;select palette&quot;
	},
	prompt: {
		selectTheme:&quot;Select the current theme&quot;,
		selectPalette:&quot;Select the current palette&quot;
	},
	tags: {
		selectTheme:'systemTheme',
		selectPalette:'systemPalette'
	}
};

config.macros.selectTheme.handler = function(place,macroName)
{
	var btn = createTiddlyButton(place,this.label[macroName],this.prompt[macroName],this.onClick);
	// want to handle palettes and themes with same code. use mode attribute to distinguish
	btn.setAttribute('mode',macroName);
};

config.macros.selectTheme.onClick = function(ev)
{
	var e = ev ? ev : window.event;
	var popup = Popup.create(this);
	var mode = this.getAttribute('mode');
	var tiddlers = store.getTaggedTiddlers(config.macros.selectTheme.tags[mode]);
	// for default
	if (mode == &quot;selectPalette&quot;) {
		var btn = createTiddlyButton(createTiddlyElement(popup,'li'),&quot;(default)&quot;,&quot;default color palette&quot;,config.macros.selectTheme.onClickTheme);
		btn.setAttribute('theme',&quot;(default)&quot;);
		btn.setAttribute('mode',mode);
	}
	for(var i=0; i&lt;tiddlers.length; i++) {
		var t = tiddlers[i].title;
		var name = store.getTiddlerSlice(t,'Name');
		var desc = store.getTiddlerSlice(t,'Description');
		var btn = createTiddlyButton(createTiddlyElement(popup,'li'), name?name:t, desc?desc:config.macros.selectTheme.label['mode'], config.macros.selectTheme.onClickTheme);
		btn.setAttribute('theme',t);
		btn.setAttribute('mode',mode);
	}
	Popup.show();
	return stopEvent(e);
};

config.macros.selectTheme.onClickTheme = function(ev)
{
	var mode = this.getAttribute('mode');
	var theme = this.getAttribute('theme');
	if (mode == 'selectTheme')
		story.switchTheme(theme);
	else // selectPalette
		config.macros.selectTheme.updatePalette(theme);
	return false;
};

config.macros.selectTheme.updatePalette = function(title)
{
	if (title != &quot;&quot;) {
		store.deleteTiddler(&quot;ColorPalette&quot;);
		if (title != &quot;(default)&quot;)
			store.saveTiddler(&quot;ColorPalette&quot;,&quot;ColorPalette&quot;,store.getTiddlerText(title),
					config.options.txtUserName,undefined,&quot;&quot;);
		refreshAll();
		if(config.options.chkAutoSave)
			saveChanges(true);
	}
};

config.macros.applyTheme = {
	label: &quot;apply&quot;,
	prompt: &quot;apply this theme or palette&quot; // i'm lazy
};

config.macros.applyTheme.handler = function(place,macroName,params,wikifier,paramString,tiddler) {
	var useTiddler = params[0] ? params[0] : tiddler.title;
	var btn = createTiddlyButton(place,this.label,this.prompt,config.macros.selectTheme.onClickTheme);
	btn.setAttribute('theme',useTiddler);
	btn.setAttribute('mode',macroName==&quot;applyTheme&quot;?&quot;selectTheme&quot;:&quot;selectPalette&quot;); // a bit untidy here
}

config.macros.selectPalette = config.macros.selectTheme;
config.macros.applyPalette = config.macros.applyTheme;

config.macros.refreshAll = { handler: function(place,macroName,params,wikifier,paramString,tiddler) {
	createTiddlyButton(place,&quot;refresh&quot;,&quot;refresh layout and styles&quot;,function() { refreshAll(); });
}};

//}}}

</pre>
</div>
<div title="SiteSubtitle" modifier="StephenWilliams" created="201103080015" changecount="1">
<pre>JavaGlue
</pre>
</div>
<div title="SiteTitle" modifier="StephenWilliams" created="201103080014" changecount="1">
<pre>AnDevCon2011 Stephen Williams</pre>
</div>
<div title="SparklinePlugin" created="200710140259" tags="systemConfig excludeLists excludeSearch" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200710140259">
<pre>/***
|''Name:''|SparklinePlugin|
|''Description:''|Sparklines macro|
***/
//{{{
if(!version.extensions.SparklinePlugin) {
version.extensions.SparklinePlugin = {installed:true};

//--
//-- Sparklines
//--

config.macros.sparkline = {};
config.macros.sparkline.handler = function(place,macroName,params)
{
	var data = [];
	var min = 0;
	var max = 0;
	var v;
	for(var t=0; t&lt;params.length; t++) {
		v = parseInt(params[t]);
		if(v &lt; min)
			min = v;
		if(v &gt; max)
			max = v;
		data.push(v);
	}
	if(data.length &lt; 1)
		return;
	var box = createTiddlyElement(place,&quot;span&quot;,null,&quot;sparkline&quot;,String.fromCharCode(160));
	box.title = data.join(&quot;,&quot;);
	var w = box.offsetWidth;
	var h = box.offsetHeight;
	box.style.paddingRight = (data.length * 2 - w) + &quot;px&quot;;
	box.style.position = &quot;relative&quot;;
	for(var d=0; d&lt;data.length; d++) {
		var tick = document.createElement(&quot;img&quot;);
		tick.border = 0;
		tick.className = &quot;sparktick&quot;;
		tick.style.position = &quot;absolute&quot;;
		tick.src = &quot;data:image/gif,GIF89a%01%00%01%00%91%FF%00%FF%FF%FF%00%00%00%C0%C0%C0%00%00%00!%F9%04%01%00%00%02%00%2C%00%00%00%00%01%00%01%00%40%02%02T%01%00%3B&quot;;
		tick.style.left = d*2 + &quot;px&quot;;
		tick.style.width = &quot;2px&quot;;
		v = Math.floor(((data[d] - min)/(max-min)) * h);
		tick.style.top = (h-v) + &quot;px&quot;;
		tick.style.height = v + &quot;px&quot;;
		box.appendChild(tick);
	}
};


}
//}}}</pre>
</div>
<div title="Ssx" modifier="StephenWilliams" created="201103081057" modified="201104040130" tags="AnDevCon2011 Ssx" changecount="30">
<pre>!Ssx, a new open source Java XML parsing library.
World premier.
This presentation can be found at: http://sdw.st/ssx.html#tag:Ssx
!Why another XML library / API?
Super Simple Xml (Ssx) was written because:
* There was (is?) no usable DOM XML parser on Android.
* The standard DOM API is broken anyway (too verbose, inefficient).
* Project needed to avoid spending a lot of time on XML parsing.  Typical use of SAX event processing, combined with complex application logic and networking, would have created too much complexity.
* There was a desire to write the most concise application code possible.  
* Parsing XML is not a big deal: stop the madness.
* XML parsing using the built-in SAX parser on Android was too slow.
* Some XML features were needed that are not typically in XML APIs (.getXml()).
* Typical XML libraries are far larger than they need to be.
!License
Written by Stephen Williams, principal at OptimaLogic.  Development was split with client.  Apache 2.0 license has been approved by all parties.
!Download
On Google Code soon.  For now, snag it from: http://sdw.st/conf/AnDevCon2011/ssx-1.0.zip
![[Concise Coding]]
!How simple can you get?
&lt;code Java&gt;
            Ssx ssx = new Ssx();
            Ssx.Xml fx;
            fx = ssx.parse(&quot;&lt;?xml version=\&quot;1.0\&quot; encoding=\&quot;UTF-8\&quot; standalone=\&quot;yes\&quot;?&gt;&lt;xml&gt;&lt;test&gt;&lt;!DOCTYPE greeting [ &lt;!ELEMENT greeting (#PCDATA)&gt; ]&gt;this &lt;![CDATA[ is &lt;nice!&gt; ]]&gt; ok?&lt;/test&gt;&lt;/xml&gt;&quot;);
            ssx.message(&quot;test:&quot;+fx.get(&quot;test&quot;));
            ssx.message(&quot;test xml:&quot;+fx.getNode(&quot;test&quot;).toXml());

            // Parsing an Atom-style media feed: A list of entries that may contain multiple links of different types.
            fx = ssx.parse(feed);
            for (Ssx.Xml entry = fx.getNode(&quot;entry&quot;); entry != null; entry = entry.nextSameName()) {
                for (Ssx.Xml link = entry.getNode(&quot;link&quot;); link != null; link = link.nextSameName()) {
                    ssx.message(&quot;Link type &quot;+link.get(&quot;@type&quot;)+&quot; href=&quot;+link.get(&quot;@href&quot;));
                }
            }
&lt;/code&gt;
!!Intro to Ssx
Ssx provides a fast, concise to use and concisely written DOM and SAX parsing library.  It is a non-validating &quot;reasonably conforming&quot; XML parser.  In a single Java file in about 1000 lines of code, written and optimized in about a week.  Ssx is meant for parsing of typical application and business data.  It is not intended as a solution to every XML need.  There are a number of permanent (DTDs) and a couple temporary restrictions for the range of XML handled.  The embedded SAX parser, which implements the org.xml.sax.XMLReader interface, is 240 lines of code (with the core parse loop written in dense &quot;paragraph mode&quot;).  This parser also directly supports efficient implementation of the toXml() method by remembering the text parsed.  In a number of cases, this can make re-serializing XML very fast.

Ssx is standard Java that also works well with Dalvik.  The only Android specific code is what is needed to find SAX when the select the built-in SAX parser is selected:
&lt;code Java&gt;
                try {
                    parser = XMLReaderFactory.createXMLReader();
                } catch (Exception e) {
                    // Try known &quot;default&quot; for Android:
                    System.setProperty(&quot;org.xml.sax.driver&quot;,&quot;org.xmlpull.v1.sax2.Driver&quot;);
                    parser = XMLReaderFactory.createXMLReader();
                }
&lt;/code&gt;
Ssx is small and simple enough to be extended as needed for a particular use.  This could include additional XPath capabilities, specialized indexing, custom validation, or integrating signing and encryption.  Internal DTD entity definitions or external entities could easily be supported.
!!!Why
XML is, at the base, a reasonably simple data format.  A number of details, like namespaces, make parsing XML somewhat interesting.  Still, existing APIs are generally far more complex than they need to be for most applications.  An application generally wants to hand data to a parser, be told if there is an error, and be able to find and retrieve data elements.  In many cases, and especially for an Android application, there is a lot to be said for having just the code needed to solve the job, leaving the kitchen sink in the kitchen.
!!! Application Data Models
Applications manage data in a variety of ways.  Sometimes these are straightforward, sometimes exotic towering frameworks must be fed and cared for.  Plumbing and overhead should not dwarf business logic.
!!!! Object Mapping
A number of methods center around creating classes for every business object, then writing code to map external representations to those objects.  This includes object relational and XML mapping.  Traditionally, developers wrote copious glue code at each layer and step.  Some modern systems try to alleviate this by using language-enabled annotations or metadata files so that this mapping can be done interpretively.  This can be helpful, but often the detailed steps and care needed to get this to work rivals manual glue code.

One must ask: Is this the only way to accomplish the business logic needed?  Is it the most efficient?  Easiest to understand and modify?  Is this the best use of the developer's time?  Consider how many lines of code need to be written at each layer for each data element introduced.  Traditionally, it is several at least, multiplied by many layers and both directions.  The ideal, and often possible case is far less than one line of code per element is needed at each layer.  

The ideal case can be described this way: An application architecture is established where a message travels from point A to point B, perhaps passing through proxies, intermediate steps that may observe or also modify or add data, perhaps storing it in message queues or in a database.  Each function, library, and application along the way may be developed separately and updated and different intervals.  If the application at point A adds a new data element, what has to change for it to get to B and perhaps back to A?  In the ideal case, only A needs to change.  When B is changed, it can react to that element.  Intermediate applications should not care that something has changed because they read what they are interested in, insert or replace data that they care about, and pass the message along.

Typical applications are not this resilient and some XML frameworks do not easily enable the best case.
!!!! Versioning &amp; Extensions
Something that is *always* an issue is how versioning and extensions are handled.  How much code has to change?  What needs to be recompiled?  When?  Ideally, something like adding an additional field to a message should be able to propagate through a system without requiring lockstep upgrades and without conflicting with existing data or databases.  XML, properly used, is one way to accomplish this.  (RDF-like graph-based semantic data is a better way, but that is another story.)
!!!! Collection Objects
A collection object is an instance of a class that manages sets of data in a structured way.  A classic example is a Map&lt;&gt; that provides a dictionary structure.  A DOM-style XML representation is a type of collection object, although the traditional DOM API is very cumbersome.

One way to avoid a lot of manual glue code or metadata is to use collection objects of some kind to represent messages and business objects.  Interestingly, these can be made arbitrarily hierarchical, just like an object hierarchy.  They can also be wrapped with very lightweight classes so that while the collection class may provide clean find/set/get, application specific methods can be added.  The result can be used in a typical object oriented fashion while writing very little code that is not business logic.  While Ssx doesn't have this level of API yet, the author has designed and implemented this type of solution very successfully in the past.
!!!! XML Idioms &amp; Loose Coupling Rules
Some key XML idioms are:
* Accept anything, complaining only if it is malformed or you can't find required items
* When passing on data received in some sense, pass on extra information even if it is not understood.
* Carefully produce data exactly to specification.
* Prefer logical structure to physical: XML can be used to represent graphs and trees.  The former are more flexible.
* Use namespaces, and semantic tagging if possible, to uniquely identify the types of elements, attributes, and relationships.
!! Writing XML
XML is usually easy to write: Simply concatenate strings, perhaps using a template that can be updated easily.  This is also usually the fastest method.  It is a big help if parsed XML or generated data structures can be easily converted into an XML document or a fragment that can be included.

In some cases, it can be helpful to have an API that allows building the XML output, perhaps in a non-linear way.  Ssx does not yet support this, but will soon.
!! How it works
Key insights used in Ssx are:
* A single set of Maps could efficiently represent the structure of an arbitrary XML tree.
* Structure is provided as map entries from the current node to the next in more than one sense: Next sibling, next sibling with same name, first child, parent.  The &quot;next&quot; operation, which is very commonly used, is very fast.
* No iterators types or objects are needed: Each object is its own iterator!
* Each element can be represented with a very lightweight object, with relationships held completely in the maps.
* The text values can be referenced as ranges of the original parsed data.  (There are some nuances here since XML is unicode and the actual source may have been bytes.)
* A toXml() method can be supported at every element in a very efficient way.  XML can be provided as a fragment or as fully formed XML with all name spaces defined properly, allowing the XML subtree to be recreated exactly in a later parse with no application fixup.
* A minimal form of XPath allows a DOM-like API to support most operations efficiently in a single line of code.
!! Android Lessons Learned
The first complete version of Ssx parsed 64K of XML in 30 ms in &quot;native Java&quot; (JDK 1.6 MacOS X).  This version took 65,000 ms to parse the same data on Android.  After optimization, the code still took the same 30 ms in native Java, but was down to 300-400 ms on Android, about the 1/10 speed ratio expected.  Speed was similar between Android 1.6 and 2.2.

Some Ssx lessons on optimizing for Dalvik:
* Avoid creating objects of any kind.  Memory allocation and garbage collection, plus the related copying, should always be minimized.  Character is expensive too.
* Unicode character conversion (byte[]-&gt;char, char-&gt;byte[]) is too expensive.  Inline code may be used in the future.
* Avoid function calls when possible.
* Using Enums is very expensive!  Don't do it in tight loops.  A local &quot;int&quot; is very fast.
* For small sets, especially with a String key, HashMap is far more expensive than TreeMap.  Use TreeMap.
* Even TreeMap is too expensive.  Much of the CPU in Ssx is spent in TreeMap.
* Direct array access is very cheap.
* Reusing objects is a key technique.
* When expandable objects are needed, simple with amortized bounds checking / reallocation are preferred.  Once a high-water mark is hit, remember it.  Use non-linear expansion in size (doubling for instance) when data varies widely.
!! [[Ssx API]]</pre>
</div>
<div title="Ssx API" modifier="StephenWilliams" created="201103090357" modified="201103090720" tags="AnDevCon2011 Ssx" changecount="6">
<pre>All retrieval methods return null when the request cannot be found, except for the versions which are given a default value to return.
&lt;code Java&gt;
public class Ssx { // Reusable object holding parse tree.  Just call parse() to reuse.
    // Determine which SAX parser is used: internal, local, or both, and whether to time parsing.
    public static void setParseType(boolean sparsep, boolean defaultParserp, boolean timeAllp);
    // Parse XML, given as a byte array.
    public Xml parse(byte[] xmlBytes, int off, int len, String nsSet) throws IOException, ParseException;
    // Parse an XML string.  'what' is information for logging.  'timed' determines whether the parse time is logged.
    public Xml parse(String what, String xml, boolean timed) throws IOException, ParseException;
    // The element node object.  Returned from a parse and most operations.
    public class Xml implements Comparable {
        // Allows objects to be compared.
        public boolean equals(Object o);
        // Returns XML equivalent of the current node.  Contained in an '&lt;xml&gt;' node with all active namespaces defined.
        public String toXml() throws UnsupportedEncodingException;
        // Returns the current node as an XML fragment.
        public String toXmlFragment() throws UnsupportedEncodingException;
        // Returns the next sibling of this element.
        public Xml next();
        // Returns the next sibling of this element that has the same name, skipping any other elements.
        public Xml nextSameName();
        // Returns the node matching the path qname.
        public Xml getNode(String qname);
	// Returns the node matching the namespace+localname.
        public Xml getNode(String ns, String localName);
        // Returns the namespace of the current node.
        String namespace();
        // Return the name of the current node.
        String name();
        // toString(), getText(), and get() all return the text for the current element.
        public String toString();
        public String getText();
        public String get();
        // Returns the text value of the given path qname.
        public String get(String qname);
        // Returns the text value of the given path qname, or the passed default value if the path is not found.
        public String get(String qname, String def);
        // Returns the text value of the given namespace+path, or default.
        public String get(String ns, String path, String def);
        // Returns the value of the given node as an int.
        public int getInt();
        public int getInt(int defaultInt);
        public int getInt(String path, int defaultInt);
        // Returns the value of the given node as a double.
        public double getDouble();
        public double getDouble(double defaultDouble);
        public double getDouble(String path, double defaultDouble);
        public double getDouble(String path);
    }
    // Turn on debugging or verbose tracing.
    public static void setDebug(boolean deb, boolean verb) { debug = deb; verbose = verb; }

    //////  Utility methods that are often missing or not quite usable.
    // Pull a stream into a string efficiently.
    public static String slurp(InputStream in) throws IOException;
    // Pull a stream into a byte array efficiently.
    public static byte[] slurpBytes(InputStream is) throws IOException;
    // These will change soon to take a pass list as proper url encoding varies depending on situation.
    // Urlencode a string
    public static String urlEncode(String s);
    // Does this character need encoding?
    public static boolean needsEncode(char c);
    // Urldecode a string
    public static String urlDecode(String s);
    // Coming soon: b64 codec
}
&lt;/code&gt;
[[Back to Ssx|Ssx 2]]</pre>
</div>
<div title="Ssx Part 2" modifier="StephenWilliams" created="201103090720" tags="AnDevCon2011 Ssx" changecount="1">
<pre>!! Coming Soon
# Namespaces are handled well for many cases.  What is currently not supported is namespace definitions that change during a single parse.  This includes a default namespace that is redefined or only defined for a subtree.  This can be improved to handle any non-pathological use of namespaces.  Namespace parsing in attribute values may also be handled.
# It is possible that the lexical events, DTD entity declarations, and other features may be important enough to be implemented.  Some of these could activate a flag to enable extra features when present to keep parsing as fast as possible in other cases.
# More incremental parsing will be supported, especially to support the streaming event DOMlet model.
# Additional convenience methods, such as date parse.
!!! Streaming Event DOMlet
The next feature to be released will be the streaming event DOMlet method.  A method to register a callback for a particular element path will allow a callback during parsing with an Ssx.Xml node for the matching element that was just completed.  The application can then process that element, returning true if the element should be removed from the parse tree to save memory.  The callback can use all normal DOM-like methods on that element or the partially completed tree as a whole.
!!! OpenEXI
OpenEXI is an open source project that combines several open source implementations of the W3C Efficient XML Interchange binary XML standard.  The author participated in the EXI working group and the XBC working group before it.  We plan to merge and refactor the existing code base, then provide an Ssx API for OpenEXI so that either XML or EXI can be produced or parsed by applications.  We have also begun the process of getting OpenEXI into the Apache Incubator.
[[http://openexi.sourceforge.net/]]
!!!! What is EXI?
EXI provides a very compact encoding of the XML infoset (i.e., the informational equivalent of an XML file) with some options.  These options allow encoding of a standalone XML file or an XML file with expected structure and data types specified with an XML Schema.  The resulting intermediate encoding can then optionally include data compression (ZLIB), applied in a particular way.  With a schema, encoding can be much more compact because the schema represents redundancy in the data and certain data can be encoded as compact binary values.

The point of all of this is to highly optimize both the processing overhead of parsing and serialization and the size of the resulting data.  Both of these greatly reduce the overall data transfer, processing, memory usage, and latency of data.

It is a common FAQ why XML + compression isn't just as good.  The two main points are that this makes processing speed even worse for XML and the result is still not as compact in many cases as EXI.  EXI greatly reduces the overhead of XML, particularly when many tags and attribute names are used.  For some XML, there is little of that so only the possibility of restricted character sets or other binary encoding would make a difference.

Another key point, and one of the key differences between EXI and most prior optimized binary formats, is that EXI can encode any XML that it is given, whether or not it matches the optional schema.
!!!! When to use
EXI is great for large amounts of complex data or for transfer of data that could be more efficient in binary, such as float or many date/times.  It is also efficient for small messages that could reduce down to a few bytes in some cases.
!! GenXDM
&lt;&lt;&lt;
GenXDM enables applications to write code that uses and manipulates XML trees without being tied to a particular XML tree representation like DOM, DOM4J, AXIOM, or any other. It also prods developers towards an immutable view of XML trees, which will make it easier and faster to work with XML across multiple cores and multiple processors.
&lt;&lt;&lt;
[[http://www.genxdm.org/]]
GenXDM is a great concept.  The GenXDM developers are interested in Ssx and OpenEXI.
!!Other Minimal XML Parsers for Java
First, the obligatory &quot;you can't do that&quot;:
&lt;&lt;&lt;
Some of these problems are problems that most
homemade or minimal solutions haven't considered, or haven't had the
full subject knowledge to implement correctly. These problems must be
handled for a parser to be a correctly working xml parser, and once
those problems are solved, you pretty much end up with something that is
similar to the projects that already exists.
&lt;&lt;&lt;
* [[http://lists.xml.org/archives/xml-dev/200401/msg00492.html]]
Some other small-ish libraries.  None seem nearly as concise and easy to use.
* [[XMLtp|http://mitglied.multimania.de/xmltp/]]
* [[sparta-xml|http://sparta-xml.sourceforge.net/]]
* [[NanoXML|http://devkix.com/nanoxml.php]]
* [[jdom|http://www.jdom.org/]]
* [[tinyxml|http://www.grinninglizard.com/tinyxml/]]
* [[piccolo|http://piccolo.sourceforge.net/]]
* [[kXML|http://kxml.sourceforge.net/about.shtml]]
!![[About Us|OptimaLogic]]
</pre>
</div>
<div title="StephenWilliams" modifier="YourName" created="201103080013" changecount="1">
<pre></pre>
</div>
<div title="StyleSheet" modifier="Jonny Gerold" created="201008102012" modified="201009042127" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201009042127">
<pre>[[StyleSheetSyntaxHighlighter]]
.viewer {
  line-height: 125%;
  font-family: serif;
  font-size: 12pt;
}</pre>
</div>
<div title="StyleSheetSyntaxHighlighter" modifier="Jonny Gerold" created="200904132302" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="200904132302">
<pre>/***
StyleSheet for ~SyntaxHighlighter
***/

/*{{{*/
.dp-highlighter
{
	font-family: &quot;Consolas&quot;, &quot;Courier New&quot;, Courier, mono, serif;
	font-size: 12px;
	background-color: #E7E5DC;
	width: 99%;
	overflow: auto;
	margin: 18px 0 18px 0 !important;
	padding-top: 1px; /* adds a little border on top when controls are hidden */
}

/* clear styles */
.dp-highlighter ol,
.dp-highlighter ol li,
.dp-highlighter ol li span 
{
	margin: 0;
	padding: 0;
	border: none;
}

.dp-highlighter a,
.dp-highlighter a:hover
{
	background: none;
	border: none;
	padding: 0;
	margin: 0;
}

.dp-highlighter .bar
{
	padding-left: 45px;
}

.dp-highlighter.collapsed .bar,
.dp-highlighter.nogutter .bar
{
	padding-left: 0px;
}

.dp-highlighter ol
{
	list-style: decimal; /* for ie */
	background-color: #fff;
	margin: 0px 0px 1px 45px !important; /* 1px bottom margin seems to fix occasional Firefox scrolling */
	padding: 0px;
	color: #5C5C5C;
}

.dp-highlighter.nogutter ol,
.dp-highlighter.nogutter ol li
{
	list-style: none !important;
	margin-left: 0px !important;
}

.dp-highlighter ol li,
.dp-highlighter .columns div
{
	list-style: decimal-leading-zero; /* better look for others, override cascade from OL */
	list-style-position: outside !important;
	border-left: 3px solid #6CE26C;
	background-color: #F8F8F8;
	color: #5C5C5C;
	padding: 0 3px 0 10px !important;
	margin: 0 !important;
	line-height: 14px;
}

.dp-highlighter.nogutter ol li,
.dp-highlighter.nogutter .columns div
{
	border: 0;
}

.dp-highlighter .columns
{
	background-color: #F8F8F8;
	color: gray;
	overflow: hidden;
	width: 100%;
}

.dp-highlighter .columns div
{
	padding-bottom: 5px;
}

.dp-highlighter ol li.alt
{
	background-color: #FFF;
	color: inherit;
}

.dp-highlighter ol li span
{
	color: black;
	background-color: inherit;
}

/* Adjust some properties when collapsed */

.dp-highlighter.collapsed ol
{
	margin: 0px;
}

.dp-highlighter.collapsed ol li
{
	display: none;
}

/* Additional modifications when in print-view */

.dp-highlighter.printing
{
	border: none;
}

.dp-highlighter.printing .tools
{
	display: none !important;
}

.dp-highlighter.printing li
{
	display: list-item !important;
}

/* Styles for the tools */

.dp-highlighter .tools
{
	padding: 3px 8px 3px 10px;
	font: 9px Verdana, Geneva, Arial, Helvetica, sans-serif;
	color: silver;
	background-color: #f8f8f8;
	padding-bottom: 10px;
	border-left: 3px solid #6CE26C;
}

.dp-highlighter.nogutter .tools
{
	border-left: 0;
}

.dp-highlighter.collapsed .tools
{
	border-bottom: 0;
}

.dp-highlighter .tools a
{
	font-size: 9px;
	color: #a0a0a0;
	background-color: inherit;
	text-decoration: none;
	margin-right: 10px;
}

.dp-highlighter .tools a:hover
{
	color: red;
	background-color: inherit;
	text-decoration: underline;
}

/* About dialog styles */

.dp-about { background-color: #fff; color: #333; margin: 0px; padding: 0px; }
.dp-about table { width: 100%; height: 100%; font-size: 11px; font-family: Tahoma, Verdana, Arial, sans-serif !important; }
.dp-about td { padding: 10px; vertical-align: top; }
.dp-about .copy { border-bottom: 1px solid #ACA899; height: 95%; }
.dp-about .title { color: red; background-color: inherit; font-weight: bold; }
.dp-about .para { margin: 0 0 4px 0; }
.dp-about .footer { background-color: #ECEADB; color: #333; border-top: 1px solid #fff; text-align: right; }
.dp-about .close { font-size: 11px; font-family: Tahoma, Verdana, Arial, sans-serif !important; background-color: #ECEADB; color: #333; width: 60px; height: 22px; }

/* Language specific styles */

.dp-highlighter .comment, .dp-highlighter .comments { color: #008200; background-color: inherit; }
.dp-highlighter .string { color: blue; background-color: inherit; }
.dp-highlighter .keyword { color: #069; font-weight: bold; background-color: inherit; }
.dp-highlighter .preprocessor { color: gray; background-color: inherit; }

/*}}}*/</pre>
</div>
<div title="SyntaxHighlighterPlugin" modifier="Jonny Gerold" created="200904132309" modified="201008112145" tags="systemConfig" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201008112145">
<pre>/***
!Metadata:
|''Name:''|SyntaxHighlighterPlugin|
|''Description:''|Code Syntax Highlighter Plugin for TiddlyWiki.|
|''Version:''|1.1.3|
|''Date:''|Oct 24, 2008|
|''Source:''|http://www.coolcode.cn/show-310-1.html|
|''Author:''|Ma Bingyao (andot (at) ujn (dot) edu (dot) cn)|
|''License:''|[[GNU Lesser General Public License|http://www.gnu.org/licenses/lgpl.txt]]|
|''~CoreVersion:''|2.4.1|
|''Browser:''|Firefox 1.5+; InternetExplorer 6.0; Safari; Opera; Chrome; etc.|

!Syntax:
{{{
&lt;code options&gt;
codes
&lt;/code&gt;
}}}

!Examples:
{{{
&lt;code java&gt;
public class HelloWorld {
    public static void main(String args[]) {
        System.out.println(&quot;HelloWorld!&quot;);
    }
}
&lt;/code&gt;
}}}

!Revision History:
|''Version''|''Date''|''Note''|
|1.1.2|Oct 15, 2008|Optimize Highlight|
|1.0.0|Oct 13, 2008|Initial release|

!Code section:
***/
//{{{
var dp={sh:{Toolbar:{},Utils:{},RegexLib:{},Brushes:{},Strings:{AboutDialog:&quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;About...&lt;/title&gt;&lt;/head&gt;&lt;body class=\&quot;dp-about\&quot;&gt;&lt;table cellspacing=\&quot;0\&quot;&gt;&lt;tr&gt;&lt;td class=\&quot;copy\&quot;&gt;&lt;p class=\&quot;title\&quot;&gt;dp.SyntaxHighlighter&lt;/div&gt;&lt;div class=\&quot;para\&quot;&gt;Version: {V}&lt;/p&gt;&lt;p&gt;&lt;a href=\&quot;http://www.dreamprojections.com/syntaxhighlighter/?ref=about\&quot; target=\&quot;_blank\&quot;&gt;http://www.dreamprojections.com/syntaxhighlighter&lt;/a&gt;&lt;/p&gt;&amp;copy;2004-2007 Alex Gorbatchev.&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td class=\&quot;footer\&quot;&gt;&lt;input type=\&quot;button\&quot; class=\&quot;close\&quot; value=\&quot;OK\&quot; onClick=\&quot;window.close()\&quot;/&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;&quot;},ClipboardSwf:null,Version:&quot;1.5.1&quot;}};dp.SyntaxHighlighter=dp.sh;dp.sh.Toolbar.Commands={ExpandSource:{label:&quot;+ expand source&quot;,check:function($){return $.collapse},func:function($,_){$.parentNode.removeChild($);_.div.className=_.div.className.replace(&quot;collapsed&quot;,&quot;&quot;)}},ViewSource:{label:&quot;view plain&quot;,func:function($,_){var A=dp.sh.Utils.FixForBlogger(_.originalCode).replace(/&lt;/g,&quot;&amp;lt;&quot;),B=window.open(&quot;&quot;,&quot;_blank&quot;,&quot;width=750, height=400, location=0, resizable=1, menubar=0, scrollbars=0&quot;);B.document.write(&quot;&lt;textarea style=\&quot;width:99%;height:99%\&quot;&gt;&quot;+A+&quot;&lt;/textarea&gt;&quot;);B.document.close()}},CopyToClipboard:{label:&quot;copy to clipboard&quot;,check:function(){return window.clipboardData!=null||dp.sh.ClipboardSwf!=null},func:function($,A){var B=dp.sh.Utils.FixForBlogger(A.originalCode).replace(/&amp;lt;/g,&quot;&lt;&quot;).replace(/&amp;gt;/g,&quot;&gt;&quot;).replace(/&amp;amp;/g,&quot;&amp;&quot;);if(window.clipboardData)window.clipboardData.setData(&quot;text&quot;,B);else if(dp.sh.ClipboardSwf!=null){var _=A.flashCopier;if(_==null){_=document.createElement(&quot;div&quot;);A.flashCopier=_;A.div.appendChild(_)}_.innerHTML=&quot;&lt;embed src=\&quot;&quot;+dp.sh.ClipboardSwf+&quot;\&quot; FlashVars=\&quot;clipboard=&quot;+encodeURIComponent(B)+&quot;\&quot; width=\&quot;0\&quot; height=\&quot;0\&quot; type=\&quot;application/x-shockwave-flash\&quot;&gt;&lt;/embed&gt;&quot;}alert(&quot;The code is in your clipboard now&quot;)}},PrintSource:{label:&quot;print&quot;,func:function($,B){var _=document.createElement(&quot;IFRAME&quot;),A=null;_.style.cssText=&quot;position:absolute;width:0px;height:0px;left:-500px;top:-500px;&quot;;document.body.appendChild(_);A=_.contentWindow.document;dp.sh.Utils.CopyStyles(A,window.document);A.write(&quot;&lt;div class=\&quot;&quot;+B.div.className.replace(&quot;collapsed&quot;,&quot;&quot;)+&quot; printing\&quot;&gt;&quot;+B.div.innerHTML+&quot;&lt;/div&gt;&quot;);A.close();_.contentWindow.focus();_.contentWindow.print();alert(&quot;Printing...&quot;);document.body.removeChild(_)}},About:{label:&quot;?&quot;,func:function(_){var A=window.open(&quot;&quot;,&quot;_blank&quot;,&quot;dialog,width=300,height=150,scrollbars=0&quot;),$=A.document;dp.sh.Utils.CopyStyles($,window.document);$.write(dp.sh.Strings.AboutDialog.replace(&quot;{V}&quot;,dp.sh.Version));$.close();A.focus()}}};dp.sh.Toolbar.Create=function(B){var A=document.createElement(&quot;DIV&quot;);A.className=&quot;tools&quot;;for(var _ in dp.sh.Toolbar.Commands){var $=dp.sh.Toolbar.Commands[_];if($.check!=null&amp;&amp;!$.check(B))continue;A.innerHTML+=&quot;&lt;a href=\&quot;#\&quot; onclick=\&quot;dp.sh.Toolbar.Command('&quot;+_+&quot;',this);return false;\&quot;&gt;&quot;+$.label+&quot;&lt;/a&gt;&quot;}return A};dp.sh.Toolbar.Command=function(_,$){var A=$;while(A!=null&amp;&amp;A.className.indexOf(&quot;dp-highlighter&quot;)==-1)A=A.parentNode;if(A!=null)dp.sh.Toolbar.Commands[_].func($,A.highlighter)};dp.sh.Utils.CopyStyles=function(A,_){var $=_.getElementsByTagName(&quot;link&quot;);for(var B=0;B&lt;$.length;B++)if($[B].rel.toLowerCase()==&quot;stylesheet&quot;)A.write(&quot;&lt;link type=\&quot;text/css\&quot; rel=\&quot;stylesheet\&quot; href=\&quot;&quot;+$[B].href+&quot;\&quot;&gt;&lt;/link&gt;&quot;)};dp.sh.Utils.FixForBlogger=function($){return(dp.sh.isBloggerMode==true)?$.replace(/&lt;br\s*\/?&gt;|&amp;lt;br\s*\/?&amp;gt;/gi,&quot;\n&quot;):$};dp.sh.RegexLib={MultiLineCComments:new RegExp(&quot;/\\*[\\s\\S]*?\\*/&quot;,&quot;gm&quot;),SingleLineCComments:new RegExp(&quot;//.*$&quot;,&quot;gm&quot;),SingleLinePerlComments:new RegExp(&quot;#.*$&quot;,&quot;gm&quot;),DoubleQuotedString:new RegExp(&quot;\&quot;(?:\\.|(\\\\\\\&quot;)|[^\\\&quot;\&quot;\\n])*\&quot;&quot;,&quot;g&quot;),SingleQuotedString:new RegExp(&quot;'(?:\\.|(\\\\\\')|[^\\''\\n])*'&quot;,&quot;g&quot;)};dp.sh.Match=function(_,$,A){this.value=_;this.index=$;this.length=_.length;this.css=A};dp.sh.Highlighter=function(){this.noGutter=false;this.addControls=true;this.collapse=false;this.tabsToSpaces=true;this.wrapColumn=80;this.showColumns=true};dp.sh.Highlighter.SortCallback=function($,_){if($.index&lt;_.index)return-1;else if($.index&gt;_.index)return 1;else if($.length&lt;_.length)return-1;else if($.length&gt;_.length)return 1;return 0};dp.sh.Highlighter.prototype.CreateElement=function(_){var $=document.createElement(_);$.highlighter=this;return $};dp.sh.Highlighter.prototype.GetMatches=function(_,B){var $=0,A=null;while((A=_.exec(this.code))!=null)this.matches[this.matches.length]=new dp.sh.Match(A[0],A.index,B)};dp.sh.Highlighter.prototype.AddBit=function($,A){if($==null||$.length==0)return;var C=this.CreateElement(&quot;SPAN&quot;);$=$.replace(/ /g,&quot;&amp;nbsp;&quot;);$=$.replace(/&lt;/g,&quot;&amp;lt;&quot;);$=$.replace(/\n/gm,&quot;&amp;nbsp;&lt;br&gt;&quot;);if(A!=null){if((/br/gi).test($)){var _=$.split(&quot;&amp;nbsp;&lt;br&gt;&quot;);for(var B=0;B&lt;_.length;B++){C=this.CreateElement(&quot;SPAN&quot;);C.className=A;C.innerHTML=_[B];this.div.appendChild(C);if(B+1&lt;_.length)this.div.appendChild(this.CreateElement(&quot;BR&quot;))}}else{C.className=A;C.innerHTML=$;this.div.appendChild(C)}}else{C.innerHTML=$;this.div.appendChild(C)}};dp.sh.Highlighter.prototype.IsInside=function(_){if(_==null||_.length==0)return false;for(var A=0;A&lt;this.matches.length;A++){var $=this.matches[A];if($==null)continue;if((_.index&gt;$.index)&amp;&amp;(_.index&lt;$.index+$.length))return true}return false};dp.sh.Highlighter.prototype.ProcessRegexList=function(){for(var $=0;$&lt;this.regexList.length;$++)this.GetMatches(this.regexList[$].regex,this.regexList[$].css)};dp.sh.Highlighter.prototype.ProcessSmartTabs=function(E){var B=E.split(&quot;\n&quot;),$=&quot;&quot;,D=4,A=&quot;\t&quot;;function _(A,E,_){var B=A.substr(0,E),C=A.substr(E+1,A.length),$=&quot;&quot;;for(var D=0;D&lt;_;D++)$+=&quot; &quot;;return B+$+C}function C(B,C){if(B.indexOf(A)==-1)return B;var D=0;while((D=B.indexOf(A))!=-1){var $=C-D%C;B=_(B,D,$)}return B}for(var F=0;F&lt;B.length;F++)$+=C(B[F],D)+&quot;\n&quot;;return $};dp.sh.Highlighter.prototype.SwitchToList=function(){var C=this.div.innerHTML.replace(/&lt;(br)\/?&gt;/gi,&quot;\n&quot;),B=C.split(&quot;\n&quot;);if(this.addControls==true)this.bar.appendChild(dp.sh.Toolbar.Create(this));if(this.showColumns){var A=this.CreateElement(&quot;div&quot;),_=this.CreateElement(&quot;div&quot;),E=10,G=1;while(G&lt;=150)if(G%E==0){A.innerHTML+=G;G+=(G+&quot;&quot;).length}else{A.innerHTML+=&quot;&amp;middot;&quot;;G++}_.className=&quot;columns&quot;;_.appendChild(A);this.bar.appendChild(_)}for(var G=0,D=this.firstLine;G&lt;B.length-1;G++,D++){var $=this.CreateElement(&quot;LI&quot;),F=this.CreateElement(&quot;SPAN&quot;);$.className=(G%2==0)?&quot;alt&quot;:&quot;&quot;;F.innerHTML=B[G]+&quot;&amp;nbsp;&quot;;$.appendChild(F);this.ol.appendChild($)}this.div.innerHTML=&quot;&quot;};dp.sh.Highlighter.prototype.Highlight=function(C){function A($){return $.replace(/^\s*(.*?)[\s\n]*$/g,&quot;$1&quot;)}function $($){return $.replace(/\n*$/,&quot;&quot;).replace(/^\n*/,&quot;&quot;)}function _(B){var E=dp.sh.Utils.FixForBlogger(B).split(&quot;\n&quot;),C=new Array(),D=new RegExp(&quot;^\\s*&quot;,&quot;g&quot;),$=1000;for(var F=0;F&lt;E.length&amp;&amp;$&gt;0;F++){if(A(E[F]).length==0)continue;var _=D.exec(E[F]);if(_!=null&amp;&amp;_.length&gt;0)$=Math.min(_[0].length,$)}if($&gt;0)for(F=0;F&lt;E.length;F++)E[F]=E[F].substr($);return E.join(&quot;\n&quot;)}function D(A,$,_){return A.substr($,_-$)}var F=0;if(C==null)C=&quot;&quot;;this.originalCode=C;this.code=$(_(C));this.div=this.CreateElement(&quot;DIV&quot;);this.bar=this.CreateElement(&quot;DIV&quot;);this.ol=this.CreateElement(&quot;OL&quot;);this.matches=new Array();this.div.className=&quot;dp-highlighter&quot;;this.div.highlighter=this;this.bar.className=&quot;bar&quot;;this.ol.start=this.firstLine;if(this.CssClass!=null)this.ol.className=this.CssClass;if(this.collapse)this.div.className+=&quot; collapsed&quot;;if(this.noGutter)this.div.className+=&quot; nogutter&quot;;if(this.tabsToSpaces==true)this.code=this.ProcessSmartTabs(this.code);this.ProcessRegexList();if(this.matches.length==0){this.AddBit(this.code,null);this.SwitchToList();this.div.appendChild(this.bar);this.div.appendChild(this.ol);return}this.matches=this.matches.sort(dp.sh.Highlighter.SortCallback);for(var E=0;E&lt;this.matches.length;E++)if(this.IsInside(this.matches[E]))this.matches[E]=null;for(E=0;E&lt;this.matches.length;E++){var B=this.matches[E];if(B==null||B.length==0)continue;this.AddBit(D(this.code,F,B.index),null);this.AddBit(B.value,B.css);F=B.index+B.length}this.AddBit(this.code.substr(F),null);this.SwitchToList();this.div.appendChild(this.bar);this.div.appendChild(this.ol)};dp.sh.Highlighter.prototype.GetKeywords=function($){return&quot;\\b&quot;+$.replace(/ /g,&quot;\\b|\\b&quot;)+&quot;\\b&quot;};dp.sh.BloggerMode=function(){dp.sh.isBloggerMode=true};dp.sh.HighlightAll=function(N,B,K,I,O,E){function A(){var $=arguments;for(var _=0;_&lt;$.length;_++){if($[_]==null)continue;if(typeof($[_])==&quot;string&quot;&amp;&amp;$[_]!=&quot;&quot;)return $[_]+&quot;&quot;;if(typeof($[_])==&quot;object&quot;&amp;&amp;$[_].value!=&quot;&quot;)return $[_].value+&quot;&quot;}return null}function J($,_){for(var A=0;A&lt;_.length;A++)if(_[A]==$)return true;return false}function L(A,B,C){var _=new RegExp(&quot;^&quot;+A+&quot;\\[(\\w+)\\]$&quot;,&quot;gi&quot;),$=null;for(var D=0;D&lt;B.length;D++)if(($=_.exec(B[D]))!=null)return $[1];return C}function C(B,A,_){var $=document.getElementsByTagName(_);for(var C=0;C&lt;$.length;C++)if($[C].getAttribute(&quot;name&quot;)==A)B.push($[C])}var T=[],P=null,M={},$=&quot;innerHTML&quot;;C(T,N,&quot;pre&quot;);C(T,N,&quot;textarea&quot;);if(T.length==0)return;for(var R in dp.sh.Brushes){var F=dp.sh.Brushes[R].Aliases;if(F==null)continue;for(var G=0;G&lt;F.length;G++)M[F[G]]=R}for(G=0;G&lt;T.length;G++){var _=T[G],U=A(_.attributes[&quot;class&quot;],_.className,_.attributes[&quot;language&quot;],_.language),Q=&quot;&quot;;if(U==null)continue;U=U.split(&quot;:&quot;);Q=U[0].toLowerCase();if(M[Q]==null)continue;P=new dp.sh.Brushes[M[Q]]();_.style.display=&quot;none&quot;;P.noGutter=(B==null)?J(&quot;nogutter&quot;,U):!B;P.addControls=(K==null)?!J(&quot;nocontrols&quot;,U):K;P.collapse=(I==null)?J(&quot;collapse&quot;,U):I;P.showColumns=(E==null)?J(&quot;showcolumns&quot;,U):E;var D=document.getElementsByTagName(&quot;head&quot;)[0];if(P.Style&amp;&amp;D){var S=document.createElement(&quot;style&quot;);S.setAttribute(&quot;type&quot;,&quot;text/css&quot;);if(S.styleSheet)S.styleSheet.cssText=P.Style;else{var H=document.createTextNode(P.Style);S.appendChild(H)}D.appendChild(S)}P.firstLine=(O==null)?parseInt(L(&quot;firstline&quot;,U,1)):O;P.Highlight(_[$]);P.source=_;_.parentNode.insertBefore(P.div,_)}};version.extensions.SyntaxHighLighterPlugin={major:1,minor:1,revision:3,date:new Date(2008,10,24)};dp.sh.ClipboardSwf=&quot;clipboard.swf&quot;;dp.sh.Highlight=function(_,Q,B,J,H,M,D){function A(){var $=arguments;for(var _=0;_&lt;$.length;_++){if($[_]==null)continue;if(typeof($[_])==&quot;string&quot;&amp;&amp;$[_]!=&quot;&quot;)return $[_]+&quot;&quot;;if(typeof($[_])==&quot;object&quot;&amp;&amp;$[_].value!=&quot;&quot;)return $[_].value+&quot;&quot;}return null}function I($,_){for(var A=0;A&lt;_.length;A++)if(_[A]==$)return true;return false}function K(A,B,C){var _=new RegExp(&quot;^&quot;+A+&quot;\\[(\\w+)\\]$&quot;,&quot;gi&quot;),$=null;for(var D=0;D&lt;B.length;D++)if(($=_.exec(B[D]))!=null)return $[1];return C}var N=null,$=&quot;innerHTML&quot;;if(this.registered==undefined){var L={};for(var O in dp.sh.Brushes){var E=dp.sh.Brushes[O].Aliases;if(E==null)continue;for(var F=0;F&lt;E.length;F++)L[E[F]]=O}this.registered=L}Q=Q.split(&quot;:&quot;);language=Q[0].toLowerCase();if(this.registered[language]==null)return;N=new dp.sh.Brushes[this.registered[language]]();_.style.display=&quot;none&quot;;N.noGutter=(B==null)?I(&quot;nogutter&quot;,Q):!B;N.addControls=(J==null)?!I(&quot;nocontrols&quot;,Q):J;N.collapse=(H==null)?I(&quot;collapse&quot;,Q):H;N.showColumns=(D==null)?I(&quot;showcolumns&quot;,Q):D;var C=document.getElementsByTagName(&quot;head&quot;)[0],P=document.getElementById(N.CssClass);if(N.Style&amp;&amp;C&amp;&amp;!P){P=document.createElement(&quot;style&quot;);P.setAttribute(&quot;id&quot;,N.CssClass);P.setAttribute(&quot;type&quot;,&quot;text/css&quot;);if(P.styleSheet)P.styleSheet.cssText=N.Style;else{var G=document.createTextNode(N.Style);P.appendChild(G)}C.appendChild(P)}N.firstLine=(M==null)?parseInt(K(&quot;firstline&quot;,Q,1)):M;N.Highlight(_[$]);N.source=_;_.parentNode.insertBefore(N.div,_)};config.formatters.push({name:&quot;SyntaxHighlighter&quot;,match:&quot;^&lt;code[\\s]+[^&gt;]+&gt;\\n&quot;,element:&quot;pre&quot;,handler:function(_){this.lookaheadRegExp=/&lt;code[\s]+([^&gt;]+)&gt;\n((?:^[^\n]*\n)+?)(^&lt;\/code&gt;$\n?)/mg;this.lookaheadRegExp.lastIndex=_.matchStart;var $=this.lookaheadRegExp.exec(_.source);if($&amp;&amp;$.index==_.matchStart){var C=$[1],B=$[2];if(config.browser.isIE)B=B.replace(/\n/g,&quot;\r&quot;);var A=createTiddlyElement(_.output,this.element,null,null,B);dp.sh.Highlight(A,C);_.nextMatch=$.index+$[0].length}}});config.formatterHelpers.enclosedTextHelper=function(_){this.lookaheadRegExp.lastIndex=_.matchStart;var $=this.lookaheadRegExp.exec(_.source);if($&amp;&amp;$.index==_.matchStart){var B=$[1];if(config.browser.isIE)B=B.replace(/\n/g,&quot;\r&quot;);var A=createTiddlyElement(_.output,this.element,null,null,B);switch(_.matchText){case&quot;/*{{{*/\n&quot;:dp.sh.Highlight(A,&quot;css&quot;);break;case&quot;//{{{\n&quot;:dp.sh.Highlight(A,&quot;js&quot;);break;case&quot;&lt;!--{{{--&gt;\n&quot;:dp.sh.Highlight(A,&quot;xml&quot;);break}_.nextMatch=$.index+$[0].length}};dp.sh.Brushes.AS3=function(){var _=&quot;class interface package&quot;,$=&quot;Array Boolean Date decodeURI decodeURIComponent encodeURI encodeURIComponent escape &quot;+&quot;int isFinite isNaN isXMLName Number Object parseFloat parseInt &quot;+&quot;String trace uint unescape XML XMLList &quot;+&quot;Infinity -Infinity NaN undefined &quot;+&quot;as delete instanceof is new typeof &quot;+&quot;break case catch continue default do each else finally for if in &quot;+&quot;label return super switch throw try while with &quot;+&quot;dynamic final internal native override private protected public static &quot;+&quot;...rest const extends function get implements namespace set &quot;+&quot;import include use &quot;+&quot;AS3 flash_proxy object_proxy &quot;+&quot;false null this true &quot;+&quot;void Null&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.MultiLineCComments,css:&quot;blockcomment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;^\\s*#.*&quot;,&quot;gm&quot;),css:&quot;preprocessor&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gm&quot;),css:&quot;definition&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;},{regex:new RegExp(&quot;var&quot;,&quot;gm&quot;),css:&quot;variable&quot;}];this.CssClass=&quot;dp-as&quot;;this.Style=&quot;.dp-as .comment { color: #009900; font-style: italic; }&quot;+&quot;.dp-as .blockcomment { color: #3f5fbf; }&quot;+&quot;.dp-as .string { color: #990000; }&quot;+&quot;.dp-as .preprocessor { color: #0033ff; }&quot;+&quot;.dp-as .definition { color: #9900cc; font-weight: bold; }&quot;+&quot;.dp-as .keyword { color: #0033ff; }&quot;+&quot;.dp-as .variable { color: #6699cc; font-weight: bold; }&quot;};dp.sh.Brushes.AS3.prototype=new dp.sh.Highlighter();dp.sh.Brushes.AS3.Aliases=[&quot;as&quot;,&quot;actionscript&quot;,&quot;ActionScript&quot;,&quot;as3&quot;,&quot;AS3&quot;];dp.sh.Brushes.Bash=function(){var _=&quot;alias bg bind break builtin cd command compgen complete continue &quot;+&quot;declare dirs disown echo enable eval exec exit export fc fg &quot;+&quot;getopts hash help history jobs kill let local logout popd printf &quot;+&quot;pushd pwd read readonly return set shift shopt source &quot;+&quot;suspend test times trap type typeset ulimit umask unalias unset wait&quot;,$=&quot;case do done elif else esac fi for function if in select then &quot;+&quot;time until while&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLinePerlComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;[()[\\]{}]&quot;,&quot;g&quot;),css:&quot;delim&quot;},{regex:new RegExp(&quot;\\$\\w+&quot;,&quot;g&quot;),css:&quot;vars&quot;},{regex:new RegExp(&quot;\\w+=&quot;,&quot;g&quot;),css:&quot;vars&quot;},{regex:new RegExp(&quot;\\s-\\w+&quot;,&quot;g&quot;),css:&quot;flag&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gm&quot;),css:&quot;builtin&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-bash&quot;;this.Style=&quot;.dp-bash .builtin {color: maroon; font-weight: bold;}&quot;+&quot;.dp-bash .comment {color: gray;}&quot;+&quot;.dp-bash .delim {font-weight: bold;}&quot;+&quot;.dp-bash .flag {color: green;}&quot;+&quot;.dp-bash .string {color: red;}&quot;+&quot;.dp-bash .vars {color: blue;}&quot;};dp.sh.Brushes.Bash.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Bash.Aliases=[&quot;bash&quot;,&quot;sh&quot;];dp.sh.Brushes.Batch=function(){var _=&quot;APPEND ATTRIB CD CHDIR CHKDSK CHOICE CLS COPY DEL ERASE DELTREE &quot;+&quot;DIR EXIT FC COMP FDISK FIND FORMAT FSUTIL HELP JOIN &quot;+&quot;LABEL LOADFIX MK MKDIR MEM MEMMAKER MORE MOVE MSD PCPARK &quot;+&quot;PRINT RD RMDIR REN SCANDISK SHARE SORT SUBST SYS &quot;+&quot;TIME DATE TREE TRUENAME TYPE UNDELETE VER XCOPY&quot;,$=&quot;DO ELSE FOR IN CALL CHOICE GOTO SHIFT PAUSE ERRORLEVEL &quot;+&quot;IF NOT EXIST LFNFOR START SETLOCAL ENDLOCAL ECHO SET&quot;;this.regexList=[{regex:new RegExp(&quot;REM.*$&quot;,&quot;gm&quot;),css:&quot;comment&quot;},{regex:new RegExp(&quot;::.*$&quot;,&quot;gm&quot;),css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;[()[\\]{}]&quot;,&quot;g&quot;),css:&quot;delim&quot;},{regex:new RegExp(&quot;%\\w+%&quot;,&quot;g&quot;),css:&quot;vars&quot;},{regex:new RegExp(&quot;%%\\w+&quot;,&quot;g&quot;),css:&quot;vars&quot;},{regex:new RegExp(&quot;\\w+=&quot;,&quot;g&quot;),css:&quot;vars&quot;},{regex:new RegExp(&quot;@\\w+&quot;,&quot;g&quot;),css:&quot;keyword&quot;},{regex:new RegExp(&quot;:\\w+&quot;,&quot;g&quot;),css:&quot;keyword&quot;},{regex:new RegExp(&quot;\\s/\\w+&quot;,&quot;g&quot;),css:&quot;flag&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gm&quot;),css:&quot;builtin&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-batch&quot;;this.Style=&quot;.dp-batch .builtin {color: maroon; font-weight: bold;}&quot;+&quot;.dp-batch .comment {color: gray;}&quot;+&quot;.dp-batch .delim {font-weight: bold;}&quot;+&quot;.dp-batch .flag {color: green;}&quot;+&quot;.dp-batch .string {color: red;}&quot;+&quot;.dp-batch .vars {color: blue;font-weight: bold;}&quot;};dp.sh.Brushes.Batch.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Batch.Aliases=[&quot;batch&quot;,&quot;dos&quot;];dp.sh.Brushes.ColdFusion=function(){this.CssClass=&quot;dp-coldfusion&quot;;this.Style=&quot;.dp-coldfusion { font: 13px \&quot;Courier New\&quot;, Courier, monospace; }&quot;+&quot;.dp-coldfusion .tag, .dp-coldfusion .tag-name { color: #990033; }&quot;+&quot;.dp-coldfusion .attribute { color: #990033; }&quot;+&quot;.dp-coldfusion .attribute-value { color: #0000FF; }&quot;+&quot;.dp-coldfusion .cfcomments { background-color: #FFFF99; color: #000000; }&quot;+&quot;.dp-coldfusion .cfscriptcomments { color: #999999; }&quot;+&quot;.dp-coldfusion .keywords { color: #0000FF; }&quot;+&quot;.dp-coldfusion .mgkeywords { color: #CC9900; }&quot;+&quot;.dp-coldfusion .numbers { color: #ff0000; }&quot;+&quot;.dp-coldfusion .strings { color: green; }&quot;;this.mgKeywords=&quot;setvalue getvalue addresult viewcollection viewstate&quot;;this.keywords=&quot;var eq neq gt gte lt lte not and or true false &quot;+&quot;abs acos addsoaprequestheader addsoapresponseheader &quot;+&quot;arrayappend arrayavg arrayclear arraydeleteat arrayinsertat &quot;+&quot;arrayisempty arraylen arraymax arraymin arraynew &quot;+&quot;arrayprepend arrayresize arrayset arraysort arraysum &quot;+&quot;arrayswap arraytolist asc asin atn binarydecode binaryencode &quot;+&quot;bitand bitmaskclear bitmaskread bitmaskset bitnot bitor bitshln &quot;+&quot;bitshrn bitxor ceiling charsetdecode charsetencode chr cjustify &quot;+&quot;compare comparenocase cos createdate createdatetime createobject &quot;+&quot;createobject createobject createobject createobject createodbcdate &quot;+&quot;createodbcdatetime createodbctime createtime createtimespan &quot;+&quot;createuuid dateadd datecompare dateconvert datediff dateformat &quot;+&quot;datepart day dayofweek dayofweekasstring dayofyear daysinmonth &quot;+&quot;daysinyear de decimalformat decrementvalue decrypt decryptbinary &quot;+&quot;deleteclientvariable directoryexists dollarformat duplicate encrypt &quot;+&quot;encryptbinary evaluate exp expandpath fileexists find findnocase &quot;+&quot;findoneof firstdayofmonth fix formatbasen generatesecretkey &quot;+&quot;getauthuser getbasetagdata getbasetaglist getbasetemplatepath &quot;+&quot;getclientvariableslist getcontextroot getcurrenttemplatepath &quot;+&quot;getdirectoryfrompath getencoding getexception getfilefrompath &quot;+&quot;getfunctionlist getgatewayhelper gethttprequestdata gethttptimestring &quot;+&quot;getk2serverdoccount getk2serverdoccountlimit getlocale &quot;+&quot;getlocaledisplayname getlocalhostip getmetadata getmetricdata &quot;+&quot;getpagecontext getprofilesections getprofilestring getsoaprequest &quot;+&quot;getsoaprequestheader getsoapresponse getsoapresponseheader &quot;+&quot;gettempdirectory gettempfile gettemplatepath gettickcount &quot;+&quot;gettimezoneinfo gettoken hash hour htmlcodeformat htmleditformat &quot;+&quot;iif incrementvalue inputbasen insert int isarray isbinary isboolean &quot;+&quot;iscustomfunction isdate isdebugmode isdefined isk2serverabroker &quot;+&quot;isk2serverdoccountexceeded isk2serveronline isleapyear islocalhost &quot;+&quot;isnumeric isnumericdate isobject isquery issimplevalue issoaprequest &quot;+&quot;isstruct isuserinrole isvalid isvalid isvalid iswddx isxml &quot;+&quot;isxmlattribute isxmldoc isxmlelem isxmlnode isxmlroot javacast &quot;+&quot;jsstringformat lcase left len listappend listchangedelims listcontains &quot;+&quot;listcontainsnocase listdeleteat listfind listfindnocase listfirst &quot;+&quot;listgetat listinsertat listlast listlen listprepend listqualify &quot;+&quot;listrest listsetat listsort listtoarray listvaluecount &quot;+&quot;listvaluecountnocase ljustify log log10 lscurrencyformat lsdateformat &quot;+&quot;lseurocurrencyformat lsiscurrency lsisdate lsisnumeric lsnumberformat &quot;+&quot;lsparsecurrency lsparsedatetime lsparseeurocurrency lsparsenumber &quot;+&quot;lstimeformat ltrim max mid min minute month monthasstring now &quot;+&quot;numberformat paragraphformat parameterexists parsedatetime pi &quot;+&quot;preservesinglequotes quarter queryaddcolumn queryaddrow querynew &quot;+&quot;querysetcell quotedvaluelist rand randomize randrange refind &quot;+&quot;refindnocase releasecomobject removechars repeatstring replace &quot;+&quot;replacelist replacenocase rereplace rereplacenocase reverse right &quot;+&quot;rjustify round rtrim second sendgatewaymessage setencoding &quot;+&quot;setlocale setprofilestring setvariable sgn sin spanexcluding &quot;+&quot;spanincluding sqr stripcr structappend structclear structcopy &quot;+&quot;structcount structdelete structfind structfindkey structfindvalue &quot;+&quot;structget structinsert structisempty structkeyarray structkeyexists &quot;+&quot;structkeylist structnew structsort structupdate tan timeformat &quot;+&quot;tobase64 tobinary toscript tostring trim ucase urldecode urlencodedformat &quot;+&quot;urlsessionformat val valuelist week wrap writeoutput xmlchildpos &quot;+&quot;xmlelemnew xmlformat xmlgetnodetype xmlnew xmlparse xmlsearch xmltransform &quot;+&quot;xmlvalidate year yesnoformat&quot;;this.stringMatches=new Array();this.attributeMatches=new Array()};dp.sh.Brushes.ColdFusion.prototype=new dp.sh.Highlighter();dp.sh.Brushes.ColdFusion.Aliases=[&quot;coldfusion&quot;,&quot;cf&quot;];dp.sh.Brushes.ColdFusion.prototype.ProcessRegexList=function(){function B(_,$){_[_.length]=$}function A(A,$){for(var _=0;_&lt;A.length;_++)if(A[_]==$)return _;return-1}var _=null,$=null;this.GetMatches(new RegExp(&quot;\\b(\\d+)&quot;,&quot;gm&quot;),&quot;numbers&quot;);this.GetMatches(new RegExp(this.GetKeywords(this.mgKeywords),&quot;igm&quot;),&quot;mgkeywords&quot;);this.GetMatches(dp.sh.RegexLib.SingleLineCComments,&quot;cfscriptcomments&quot;);this.GetMatches(dp.sh.RegexLib.MultiLineCComments,&quot;cfscriptcomments&quot;);this.GetMatches(new RegExp(&quot;(&amp;lt;|&lt;)!---[\\s\\S]*?---(&amp;gt;|&gt;)&quot;,&quot;gm&quot;),&quot;cfcomments&quot;);$=new RegExp(&quot;(cfset\\s*)?([:\\w-.]+)\\s*=\\s*(\&quot;.*?\&quot;|'.*?')*&quot;,&quot;gm&quot;);while((_=$.exec(this.code))!=null){if(_[1]!=undefined&amp;&amp;_[1]!=&quot;&quot;)continue;if(_[3]!=undefined&amp;&amp;_[3]!=&quot;&quot;&amp;&amp;_[3]!=&quot;\&quot;\&quot;&quot;&amp;&amp;_[3]!=&quot;''&quot;){B(this.matches,new dp.sh.Match(_[2],_.index,&quot;attribute&quot;));B(this.matches,new dp.sh.Match(_[3],_.index+_[0].indexOf(_[3]),&quot;attribute-value&quot;));B(this.stringMatches,_[3]);B(this.attributeMatches,_[2])}}this.GetMatches(new RegExp(&quot;(&amp;lt;|&lt;)/*\\?*(?!\\!)|/*\\?*(&amp;gt;|&gt;)&quot;,&quot;gm&quot;),&quot;tag&quot;);$=new RegExp(&quot;(?:&amp;lt;|&lt;)/*\\?*\\s*([:\\w-.]+)&quot;,&quot;gm&quot;);while((_=$.exec(this.code))!=null)B(this.matches,new dp.sh.Match(_[1],_.index+_[0].indexOf(_[1]),&quot;tag-name&quot;));$=new RegExp(this.GetKeywords(this.keywords),&quot;igm&quot;);while((_=$.exec(this.code))!=null)if(A(this.attributeMatches,_[0])==-1)B(this.matches,new dp.sh.Match(_[0],_.index,&quot;keywords&quot;));$=new RegExp(&quot;cfset\\s*.*(\&quot;.*?\&quot;|'.*?')&quot;,&quot;gm&quot;);while((_=$.exec(this.code))!=null)if(_[1]!=undefined&amp;&amp;_[1]!=&quot;&quot;){B(this.matches,new dp.sh.Match(_[1],_.index+_[0].indexOf(_[1]),&quot;strings&quot;));B(this.stringMatches,_[1])}while((_=dp.sh.RegexLib.DoubleQuotedString.exec(this.code))!=null)if(A(this.stringMatches,_[0])==-1)B(this.matches,new dp.sh.Match(_[0],_.index,&quot;strings&quot;));while((_=dp.sh.RegexLib.SingleQuotedString.exec(this.code))!=null)if(A(this.stringMatches,_[0])==-1)B(this.matches,new dp.sh.Match(_[0],_.index,&quot;strings&quot;))};dp.sh.Brushes.Cpp=function(){var _=&quot;ATOM BOOL BOOLEAN BYTE CHAR COLORREF DWORD DWORDLONG DWORD_PTR &quot;+&quot;DWORD32 DWORD64 FLOAT HACCEL HALF_PTR HANDLE HBITMAP HBRUSH &quot;+&quot;HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP &quot;+&quot;HENHMETAFILE HFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY &quot;+&quot;HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRESULT &quot;+&quot;HRGN HRSRC HSZ HWINSTA HWND INT INT_PTR INT32 INT64 LANGID LCID LCTYPE &quot;+&quot;LGRPID LONG LONGLONG LONG_PTR LONG32 LONG64 LPARAM LPBOOL LPBYTE LPCOLORREF &quot;+&quot;LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR &quot;+&quot;LPVOID LPWORD LPWSTR LRESULT PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR &quot;+&quot;PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR PHANDLE PHKEY PINT &quot;+&quot;PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 &quot;+&quot;POINTER_64 PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR &quot;+&quot;PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 &quot;+&quot;PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SHORT &quot;+&quot;SIZE_T SSIZE_T TBYTE TCHAR UCHAR UHALF_PTR UINT UINT_PTR UINT32 UINT64 ULONG &quot;+&quot;ULONGLONG ULONG_PTR ULONG32 ULONG64 USHORT USN VOID WCHAR WORD WPARAM WPARAM WPARAM &quot;+&quot;char bool short int __int32 __int64 __int8 __int16 long float double __wchar_t &quot;+&quot;clock_t _complex _dev_t _diskfree_t div_t ldiv_t _exception _EXCEPTION_POINTERS &quot;+&quot;FILE _finddata_t _finddatai64_t _wfinddata_t _wfinddatai64_t __finddata64_t &quot;+&quot;__wfinddata64_t _FPIEEE_RECORD fpos_t _HEAPINFO _HFILE lconv intptr_t &quot;+&quot;jmp_buf mbstate_t _off_t _onexit_t _PNH ptrdiff_t _purecall_handler &quot;+&quot;sig_atomic_t size_t _stat __stat64 _stati64 terminate_function &quot;+&quot;time_t __time64_t _timeb __timeb64 tm uintptr_t _utimbuf &quot;+&quot;va_list wchar_t wctrans_t wctype_t wint_t signed&quot;,$=&quot;break case catch class const __finally __exception __try &quot;+&quot;const_cast continue private public protected __declspec &quot;+&quot;default delete deprecated dllexport dllimport do dynamic_cast &quot;+&quot;else enum explicit extern if for friend goto inline &quot;+&quot;mutable naked namespace new noinline noreturn nothrow &quot;+&quot;register reinterpret_cast return selectany &quot;+&quot;sizeof static static_cast struct switch template this &quot;+&quot;thread throw true false try typedef typeid typename union &quot;+&quot;using uuid virtual void volatile whcar_t while&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.MultiLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;^ *#.*&quot;,&quot;gm&quot;),css:&quot;preprocessor&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gm&quot;),css:&quot;datatypes&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-cpp&quot;;this.Style=&quot;.dp-cpp .datatypes { color: #2E8B57; font-weight: bold; }&quot;};dp.sh.Brushes.Cpp.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Cpp.Aliases=[&quot;cpp&quot;,&quot;c&quot;,&quot;c++&quot;];dp.sh.Brushes.CSharp=function(){var $=&quot;abstract as base bool break byte case catch char checked class const &quot;+&quot;continue decimal default delegate do double else enum event explicit &quot;+&quot;extern false finally fixed float for foreach get goto if implicit in int &quot;+&quot;interface internal is lock long namespace new null object operator out &quot;+&quot;override params private protected public readonly ref return sbyte sealed set &quot;+&quot;short sizeof stackalloc static string struct switch this throw true try &quot;+&quot;typeof uint ulong unchecked unsafe ushort using virtual void while&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.MultiLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;^\\s*#.*&quot;,&quot;gm&quot;),css:&quot;preprocessor&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-c&quot;;this.Style=&quot;.dp-c .vars { color: #d00; }&quot;};dp.sh.Brushes.CSharp.prototype=new dp.sh.Highlighter();dp.sh.Brushes.CSharp.Aliases=[&quot;c#&quot;,&quot;c-sharp&quot;,&quot;csharp&quot;];dp.sh.Brushes.CSS=function(){var _=&quot;ascent azimuth background-attachment background-color background-image background-position &quot;+&quot;background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top &quot;+&quot;border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color &quot;+&quot;border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width &quot;+&quot;border-bottom-width border-left-width border-width border cap-height caption-side centerline clear clip color &quot;+&quot;content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display &quot;+&quot;elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font &quot;+&quot;height letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top &quot;+&quot;margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width orphans &quot;+&quot;outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page &quot;+&quot;page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position &quot;+&quot;quotes richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress &quot;+&quot;table-layout text-align text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em &quot;+&quot;vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index&quot;,$=&quot;above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder &quot;+&quot;both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed &quot;+&quot;continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero default digits disc dotted double &quot;+&quot;embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia &quot;+&quot;gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic &quot;+&quot;justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha &quot;+&quot;lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower &quot;+&quot;navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset &quot;+&quot;outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side &quot;+&quot;rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow &quot;+&quot;small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize &quot;+&quot;table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal &quot;+&quot;text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin &quot;+&quot;upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow&quot;,A=&quot;[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif&quot;;this.regexList=[{regex:dp.sh.RegexLib.MultiLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;\\#[a-zA-Z0-9]{3,6}&quot;,&quot;g&quot;),css:&quot;value&quot;},{regex:new RegExp(&quot;(-?\\d+)(.\\d+)?(px|em|pt|:|%|)&quot;,&quot;g&quot;),css:&quot;value&quot;},{regex:new RegExp(&quot;!important&quot;,&quot;g&quot;),css:&quot;important&quot;},{regex:new RegExp(this.GetKeywordsCSS(_),&quot;gm&quot;),css:&quot;keyword&quot;},{regex:new RegExp(this.GetValuesCSS($),&quot;g&quot;),css:&quot;value&quot;},{regex:new RegExp(this.GetValuesCSS(A),&quot;g&quot;),css:&quot;value&quot;}];this.CssClass=&quot;dp-css&quot;;this.Style=&quot;.dp-css .value { color: black; }&quot;+&quot;.dp-css .important { color: red; }&quot;};dp.sh.Highlighter.prototype.GetKeywordsCSS=function($){return&quot;\\b([a-z_]|)&quot;+$.replace(/ /g,&quot;(?=:)\\b|\\b([a-z_\\*]|\\*|)&quot;)+&quot;(?=:)\\b&quot;};dp.sh.Highlighter.prototype.GetValuesCSS=function($){return&quot;\\b&quot;+$.replace(/ /g,&quot;(?!-)(?!:)\\b|\\b()&quot;)+&quot;:\\b&quot;};dp.sh.Brushes.CSS.prototype=new dp.sh.Highlighter();dp.sh.Brushes.CSS.Aliases=[&quot;css&quot;];dp.sh.Brushes.Delphi=function(){var $=&quot;abs addr and ansichar ansistring array as asm begin boolean byte cardinal &quot;+&quot;case char class comp const constructor currency destructor div do double &quot;+&quot;downto else end except exports extended false file finalization finally &quot;+&quot;for function goto if implementation in inherited int64 initialization &quot;+&quot;integer interface is label library longint longword mod nil not object &quot;+&quot;of on or packed pansichar pansistring pchar pcurrency pdatetime pextended &quot;+&quot;pint64 pointer private procedure program property pshortstring pstring &quot;+&quot;pvariant pwidechar pwidestring protected public published raise real real48 &quot;+&quot;record repeat set shl shortint shortstring shr single smallint string then &quot;+&quot;threadvar to true try type unit until uses val var varirnt while widechar &quot;+&quot;widestring with word write writeln xor&quot;;this.regexList=[{regex:new RegExp(&quot;\\(\\*[\\s\\S]*?\\*\\)&quot;,&quot;gm&quot;),css:&quot;comment&quot;},{regex:new RegExp(&quot;{(?!\\$)[\\s\\S]*?}&quot;,&quot;gm&quot;),css:&quot;comment&quot;},{regex:dp.sh.RegexLib.SingleLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;\\{\\$[a-zA-Z]+ .+\\}&quot;,&quot;g&quot;),css:&quot;directive&quot;},{regex:new RegExp(&quot;\\b[\\d\\.]+\\b&quot;,&quot;g&quot;),css:&quot;number&quot;},{regex:new RegExp(&quot;\\$[a-zA-Z0-9]+\\b&quot;,&quot;g&quot;),css:&quot;number&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-delphi&quot;;this.Style=&quot;.dp-delphi .number { color: blue; }&quot;+&quot;.dp-delphi .directive { color: #008284; }&quot;+&quot;.dp-delphi .vars { color: #000; }&quot;};dp.sh.Brushes.Delphi.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Delphi.Aliases=[&quot;delphi&quot;,&quot;pascal&quot;];dp.sh.Brushes.Java=function(){var $=&quot;abstract assert boolean break byte case catch char class const &quot;+&quot;continue default do double else enum extends &quot;+&quot;false final finally float for goto if implements import &quot;+&quot;instanceof int interface long native new null &quot;+&quot;package private protected public return &quot;+&quot;short static strictfp super switch synchronized this throw throws true &quot;+&quot;transient try void volatile while&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.MultiLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;\\b([\\d]+(\\.[\\d]+)?|0x[a-f0-9]+)\\b&quot;,&quot;gi&quot;),css:&quot;number&quot;},{regex:new RegExp(&quot;(?!\\@interface\\b)\\@[\\$\\w]+\\b&quot;,&quot;g&quot;),css:&quot;annotation&quot;},{regex:new RegExp(&quot;\\@interface\\b&quot;,&quot;g&quot;),css:&quot;keyword&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-j&quot;;this.Style=&quot;.dp-j .annotation { color: #646464; }&quot;+&quot;.dp-j .number { color: #C00000; }&quot;};dp.sh.Brushes.Java.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Java.Aliases=[&quot;java&quot;];dp.sh.Brushes.JScript=function(){var $=&quot;abstract boolean break byte case catch char class const continue debugger &quot;+&quot;default delete do double else enum export extends false final finally float &quot;+&quot;for function goto if implements import in instanceof int interface long native &quot;+&quot;new null package private protected public return short static super switch &quot;+&quot;synchronized this throw throws transient true try typeof var void volatile while with&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.MultiLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;^\\s*#.*&quot;,&quot;gm&quot;),css:&quot;preprocessor&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-c&quot;};dp.sh.Brushes.JScript.prototype=new dp.sh.Highlighter();dp.sh.Brushes.JScript.Aliases=[&quot;js&quot;,&quot;jscript&quot;,&quot;javascript&quot;];dp.sh.Brushes.Lua=function(){var $=&quot;break do end else elseif function if local nil not or repeat return and then until while this&quot;,_=&quot;math\\.\\w+ string\\.\\w+ os\\.\\w+ debug\\.\\w+ io\\.\\w+ error fopen dofile coroutine\\.\\w+ arg getmetatable ipairs loadfile loadlib loadstring longjmp print rawget rawset seek setmetatable assert tonumber tostring&quot;;this.regexList=[{regex:new RegExp(&quot;--\\[\\[[\\s\\S]*\\]\\]--&quot;,&quot;gm&quot;),css:&quot;comment&quot;},{regex:new RegExp(&quot;--[^\\[]{2}.*$&quot;,&quot;gm&quot;),css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gm&quot;),css:&quot;func&quot;},];this.CssClass=&quot;dp-lua&quot;};dp.sh.Brushes.Lua.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Lua.Aliases=[&quot;lua&quot;];dp.sh.Brushes.Mxml=function(){this.CssClass=&quot;dp-mxml&quot;;this.Style=&quot;.dp-mxml .cdata { color: #000000; }&quot;+&quot;.dp-mxml .tag { color : #0000ff; }&quot;+&quot;.dp-mxml .tag-name { color: #0000ff; }&quot;+&quot;.dp-mxml .script { color: green; }&quot;+&quot;.dp-mxml .metadata { color: green; }&quot;+&quot;.dp-mxml .attribute { color: #000000; }&quot;+&quot;.dp-mxml .attribute-value { color: #990000; }&quot;+&quot;.dp-mxml .trace { color: #cc6666; }&quot;+&quot;.dp-mxml .var { color: #6699cc; }&quot;+&quot;.dp-mxml .comment { color: #009900; }&quot;+&quot;.dp-mxml .string { color: #990000; }&quot;+&quot;.dp-mxml .keyword { color: blue; }&quot;};dp.sh.Brushes.Mxml.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Mxml.Aliases=[&quot;mxml&quot;];dp.sh.Brushes.Mxml.prototype.ProcessRegexList=function(){function H(_,$){_[_.length]=$}function B(B,_){var A=0,$=false;for(A=0;A&lt;B.length;A++)if(_.index&gt;B[A].firstIndex&amp;&amp;_.index&lt;B[A].lastIndex)$=true;return $}var $=0,F=null,D=null,A=null,C=&quot;&quot;,E=new Array(),_=&quot;abstract boolean break byte case catch char class const continue debugger &quot;+&quot;default delete do double else enum export extends false final finally float &quot;+&quot;for function goto if implements import in instanceof int interface long native &quot;+&quot;new null package private protected public return short static super switch &quot;+&quot;synchronized this throw throws transient true try typeof var void volatile while with&quot;,G=[{regex:dp.sh.RegexLib.SingleLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.MultiLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;^\\s*#.*&quot;,&quot;gm&quot;),css:&quot;preprocessor&quot;},{regex:new RegExp(this.GetKeywords(&quot;trace&quot;),&quot;gm&quot;),css:&quot;trace&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gm&quot;),css:&quot;keyword&quot;}];A=new RegExp(&quot;&amp;lt;\\!\\[CDATA\\[(.|\\s)*?\\]\\]&amp;gt;&quot;,&quot;gm&quot;);while((F=A.exec(this.code))!=null){C=F[0].substr(0,12);H(this.matches,new dp.sh.Match(C,F.index,&quot;cdata&quot;));C=F[0].substr(12,F[0].length-12-6);for(var I=0;I&lt;G.length;I++)while((D=G[I].regex.exec(C))!=null)H(this.matches,new dp.sh.Match(D[0],F.index+12+D.index,G[I].css));C=F[0].substr(F[0].length-6,6);H(this.matches,new dp.sh.Match(C,F.index+F[0].length-6,&quot;cdata&quot;));E.push({firstIndex:F.index,lastIndex:F.index+F[0].length-1})}this.GetMatches(new RegExp(&quot;(&amp;lt;|&lt;)!--\\s*.*?\\s*--(&amp;gt;|&gt;)&quot;,&quot;gm&quot;),&quot;comments&quot;);A=new RegExp(&quot;([:\\w-.]+)\\s*=\\s*(\&quot;.*?\&quot;|'.*?'|\\w+)*|(\\w+)&quot;,&quot;gm&quot;);while((F=A.exec(this.code))!=null){if(F[1]==null)continue;if(B(E,F))continue;H(this.matches,new dp.sh.Match(F[1],F.index,&quot;attribute&quot;));if(F[2]!=undefined)H(this.matches,new dp.sh.Match(F[2],F.index+F[0].indexOf(F[2]),&quot;attribute-value&quot;))}A=new RegExp(&quot;(?:&amp;lt;|&lt;)/*\\?*\\s*([:\\w-.]+)&quot;,&quot;gm&quot;);while((F=A.exec(this.code))!=null){if(B(E,F))continue;C=F[0].substr(4,F[0].length-4);switch(C){case&quot;mx:Script&quot;:case&quot;/mx:Script&quot;:H(this.matches,new dp.sh.Match(F[0]+&quot;&amp;gt;&quot;,F.index,&quot;script&quot;));break;case&quot;mx:Metadata&quot;:case&quot;/mx:Metadata&quot;:H(this.matches,new dp.sh.Match(F[0]+&quot;&amp;gt;&quot;,F.index,&quot;metadata&quot;));break;default:H(this.matches,new dp.sh.Match(F[0],F.index,&quot;tag-name&quot;));break}}A=new RegExp(&quot;\\?&amp;gt;|&amp;gt;|/&amp;gt;&quot;,&quot;gm&quot;);while((F=A.exec(this.code))!=null){if(B(E,F))continue;H(this.matches,new dp.sh.Match(F[0],F.index,&quot;tag&quot;))}};dp.sh.Brushes.Perl=function(){var _=&quot;abs accept alarm atan2 bind binmode bless caller chdir chmod chomp chop chown chr chroot close closedir connect cos crypt dbmclose dbmopen defined delete dump each endgrent endhostent endnetent endprotoent endpwent endservent eof exec exists exp fcntl fileno flock fork format formline getc getgrent getgrgid getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr getnetbyname getnetent getpeername getpgrp getppid getpriority getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid getservbyname getservbyport getservent getsockname getsockopt glob gmtime grep hex import index int ioctl join keys kill lc lcfirst length link listen localtime lock log lstat m map mkdir msgctl msgget msgrcv msgsnd no oct open opendir ord pack pipe pop pos print printf prototype push q qq quotemeta qw qx rand read readdir readline readlink readpipe recv ref rename reset reverse rewinddir rindex rmdir scalar seek seekdir semctl semget semop send setgrent sethostent setnetent setpgrp setpriority setprotoent setpwent setservent setsockopt shift shmctl shmget shmread shmwrite shutdown sin sleep socket socketpair sort splice split sprintf sqrt srand stat study sub substr symlink syscall sysopen sysread sysseek system syswrite tell telldir tie tied time times tr truncate uc ucfirst umask undef unlink unpack unshift untie utime values vec waitpid wantarray warn write qr&quot;,$=&quot;s select goto die do package redo require return continue for foreach last next wait while use if else elsif eval exit unless switch case&quot;,A=&quot;my our local&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLinePerlComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;(\\$|@|%)\\w+&quot;,&quot;g&quot;),css:&quot;vars&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gmi&quot;),css:&quot;func&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;},{regex:new RegExp(this.GetKeywords(A),&quot;gm&quot;),css:&quot;declarations&quot;}];this.CssClass=&quot;dp-perl&quot;};dp.sh.Brushes.Perl.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Perl.Aliases=[&quot;perl&quot;];dp.sh.Brushes.Php=function(){var _=&quot;abs acos acosh addcslashes addslashes &quot;+&quot;array_change_key_case array_chunk array_combine array_count_values array_diff &quot;+&quot;array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill &quot;+&quot;array_filter array_flip array_intersect array_intersect_assoc array_intersect_key &quot;+&quot;array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map &quot;+&quot;array_merge array_merge_recursive array_multisort array_pad array_pop array_product &quot;+&quot;array_push array_rand array_reduce array_reverse array_search array_shift &quot;+&quot;array_slice array_splice array_sum array_udiff array_udiff_assoc &quot;+&quot;array_udiff_uassoc array_uintersect array_uintersect_assoc &quot;+&quot;array_uintersect_uassoc array_unique array_unshift array_values array_walk &quot;+&quot;array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert &quot;+&quot;basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress &quot;+&quot;bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir &quot;+&quot;checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists &quot;+&quot;closedir closelog copy cos cosh count count_chars date decbin dechex decoct &quot;+&quot;deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log &quot;+&quot;error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded &quot;+&quot;feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents &quot;+&quot;fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype &quot;+&quot;floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf &quot;+&quot;fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname &quot;+&quot;gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt &quot;+&quot;getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext &quot;+&quot;gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set &quot;+&quot;interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double &quot;+&quot;is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long &quot;+&quot;is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault &quot;+&quot;is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br &quot;+&quot;parse_ini_file parse_str parse_url passthru pathinfo readlink realpath rewind rewinddir rmdir &quot;+&quot;round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split &quot;+&quot;str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes &quot;+&quot;stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk &quot;+&quot;strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime &quot;+&quot;strtoupper strtr strval substr substr_compare&quot;,$=&quot;and or xor __FILE__ __LINE__ array as break case &quot;+&quot;cfunction class const continue declare default die do else &quot;+&quot;elseif empty enddeclare endfor endforeach endif endswitch endwhile &quot;+&quot;extends for foreach function include include_once global if &quot;+&quot;new old_function return static switch use require require_once &quot;+&quot;var while __FUNCTION__ __CLASS__ &quot;+&quot;__METHOD__ abstract interface public implements extends private protected throw&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.MultiLineCComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;\\$\\w+&quot;,&quot;g&quot;),css:&quot;vars&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gmi&quot;),css:&quot;func&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-c&quot;};dp.sh.Brushes.Php.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Php.Aliases=[&quot;php&quot;];dp.sh.Brushes.Python=function(){var $=&quot;and assert break class continue def del elif else &quot;+&quot;except exec finally for from global if import in is &quot;+&quot;lambda not or pass print raise return try yield while&quot;,_=&quot;None True False self cls class_&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLinePerlComments,css:&quot;comment&quot;},{regex:new RegExp(&quot;^\\s*@\\w+&quot;,&quot;gm&quot;),css:&quot;decorator&quot;},{regex:new RegExp(&quot;(['\&quot;]{3})([^\\1])*?\\1&quot;,&quot;gm&quot;),css:&quot;comment&quot;},{regex:new RegExp(&quot;\&quot;(?!\&quot;)(?:\\.|\\\\\\\&quot;|[^\\\&quot;\&quot;\\n\\r])*\&quot;&quot;,&quot;gm&quot;),css:&quot;string&quot;},{regex:new RegExp(&quot;'(?!')*(?:\\.|(\\\\\\')|[^\\''\\n\\r])*'&quot;,&quot;gm&quot;),css:&quot;string&quot;},{regex:new RegExp(&quot;\\b\\d+\\.?\\w*&quot;,&quot;g&quot;),css:&quot;number&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gm&quot;),css:&quot;special&quot;}];this.CssClass=&quot;dp-py&quot;;this.Style=&quot;.dp-py .builtins { color: #ff1493; }&quot;+&quot;.dp-py .magicmethods { color: #808080; }&quot;+&quot;.dp-py .exceptions { color: brown; }&quot;+&quot;.dp-py .types { color: brown; font-style: italic; }&quot;+&quot;.dp-py .commonlibs { color: #8A2BE2; font-style: italic; }&quot;};dp.sh.Brushes.Python.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Python.Aliases=[&quot;py&quot;,&quot;python&quot;];dp.sh.Brushes.Ruby=function(){var $=&quot;alias and BEGIN begin break case class def define_method defined do each else elsif &quot;+&quot;END end ensure false for if in module new next nil not or raise redo rescue retry return &quot;+&quot;self super then throw true undef unless until when while yield&quot;,_=&quot;Array Bignum Binding Class Continuation Dir Exception FalseClass File::Stat File Fixnum Fload &quot;+&quot;Hash Integer IO MatchData Method Module NilClass Numeric Object Proc Range Regexp String Struct::TMS Symbol &quot;+&quot;ThreadGroup Thread Time TrueClass&quot;;this.regexList=[{regex:dp.sh.RegexLib.SingleLinePerlComments,css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;:[a-z][A-Za-z0-9_]*&quot;,&quot;g&quot;),css:&quot;symbol&quot;},{regex:new RegExp(&quot;(\\$|@@|@)\\w+&quot;,&quot;g&quot;),css:&quot;variable&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gm&quot;),css:&quot;builtin&quot;}];this.CssClass=&quot;dp-rb&quot;;this.Style=&quot;.dp-rb .symbol { color: #a70; }&quot;+&quot;.dp-rb .variable { color: #a70; font-weight: bold; }&quot;};dp.sh.Brushes.Ruby.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Ruby.Aliases=[&quot;ruby&quot;,&quot;rails&quot;,&quot;ror&quot;];dp.sh.Brushes.Sql=function(){var _=&quot;abs avg case cast coalesce convert count current_timestamp &quot;+&quot;current_user day isnull left lower month nullif replace right &quot;+&quot;session_user space substring sum system_user upper user year&quot;,$=&quot;absolute action add after alter as asc at authorization begin bigint &quot;+&quot;binary bit by cascade char character check checkpoint close collate &quot;+&quot;column commit committed connect connection constraint contains continue &quot;+&quot;create cube current current_date current_time cursor database date &quot;+&quot;deallocate dec decimal declare default delete desc distinct double drop &quot;+&quot;dynamic else end end-exec escape except exec execute false fetch first &quot;+&quot;float for force foreign forward free from full function global goto grant &quot;+&quot;group grouping having hour ignore index inner insensitive insert instead &quot;+&quot;int integer intersect into is isolation key last level load local max min &quot;+&quot;minute modify move name national nchar next no numeric of off on only &quot;+&quot;open option order out output partial password precision prepare primary &quot;+&quot;prior privileges procedure public read real references relative repeatable &quot;+&quot;restrict return returns revoke rollback rollup rows rule schema scroll &quot;+&quot;second section select sequence serializable set size smallint static &quot;+&quot;statistics table temp temporary then time timestamp to top transaction &quot;+&quot;translation trigger true truncate uncommitted union unique update values &quot;+&quot;varchar varying view when where with work&quot;,A=&quot;all and any between cross in join like not null or outer some&quot;;this.regexList=[{regex:new RegExp(&quot;--(.*)$&quot;,&quot;gm&quot;),css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:dp.sh.RegexLib.SingleQuotedString,css:&quot;string&quot;},{regex:new RegExp(this.GetKeywords(_),&quot;gmi&quot;),css:&quot;func&quot;},{regex:new RegExp(this.GetKeywords(A),&quot;gmi&quot;),css:&quot;op&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gmi&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-sql&quot;;this.Style=&quot;.dp-sql .func { color: #ff1493; }&quot;+&quot;.dp-sql .op { color: #808080; }&quot;};dp.sh.Brushes.Sql.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Sql.Aliases=[&quot;sql&quot;];dp.sh.Brushes.Vb=function(){var $=&quot;AddHandler AddressOf AndAlso Alias And Ansi As Assembly Auto &quot;+&quot;Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate &quot;+&quot;CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType &quot;+&quot;Date Decimal Declare Default Delegate Dim DirectCast Do Double Each &quot;+&quot;Else ElseIf End Enum Erase Error Event Exit False Finally For Friend &quot;+&quot;Function Get GetType GoSub GoTo Handles If Implements Imports In &quot;+&quot;Inherits Integer Interface Is Let Lib Like Long Loop Me Mod Module &quot;+&quot;MustInherit MustOverride MyBase MyClass Namespace New Next Not Nothing &quot;+&quot;NotInheritable NotOverridable Object On Option Optional Or OrElse &quot;+&quot;Overloads Overridable Overrides ParamArray Preserve Private Property &quot;+&quot;Protected Public RaiseEvent ReadOnly ReDim REM RemoveHandler Resume &quot;+&quot;Return Select Set Shadows Shared Short Single Static Step Stop String &quot;+&quot;Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until &quot;+&quot;Variant When While With WithEvents WriteOnly Xor&quot;;this.regexList=[{regex:new RegExp(&quot;'.*$&quot;,&quot;gm&quot;),css:&quot;comment&quot;},{regex:dp.sh.RegexLib.DoubleQuotedString,css:&quot;string&quot;},{regex:new RegExp(&quot;^\\s*#.*&quot;,&quot;gm&quot;),css:&quot;preprocessor&quot;},{regex:new RegExp(this.GetKeywords($),&quot;gm&quot;),css:&quot;keyword&quot;}];this.CssClass=&quot;dp-vb&quot;};dp.sh.Brushes.Vb.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Vb.Aliases=[&quot;vb&quot;,&quot;vb.net&quot;];dp.sh.Brushes.Xml=function(){this.CssClass=&quot;dp-xml&quot;;this.Style=&quot;.dp-xml .cdata { color: #ff1493; }&quot;+&quot;.dp-xml .tag, .dp-xml .tag-name { color: #069; font-weight: bold; }&quot;+&quot;.dp-xml .attribute { color: red; }&quot;+&quot;.dp-xml .attribute-value { color: blue; }&quot;};dp.sh.Brushes.Xml.prototype=new dp.sh.Highlighter();dp.sh.Brushes.Xml.Aliases=[&quot;xml&quot;,&quot;xhtml&quot;,&quot;xslt&quot;,&quot;html&quot;,&quot;xhtml&quot;];dp.sh.Brushes.Xml.prototype.ProcessRegexList=function(){function B(_,$){_[_.length]=$}var $=0,A=null,_=null;this.GetMatches(new RegExp(&quot;(&amp;lt;|&lt;)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](&amp;gt;|&gt;)&quot;,&quot;gm&quot;),&quot;cdata&quot;);this.GetMatches(new RegExp(&quot;(&amp;lt;|&lt;)!--\\s*.*?\\s*--(&amp;gt;|&gt;)&quot;,&quot;gm&quot;),&quot;comments&quot;);_=new RegExp(&quot;([:\\w-.]+)\\s*=\\s*(\&quot;.*?\&quot;|'.*?'|\\w+)*|(\\w+)&quot;,&quot;gm&quot;);while((A=_.exec(this.code))!=null){if(A[1]==null)continue;B(this.matches,new dp.sh.Match(A[1],A.index,&quot;attribute&quot;));if(A[2]!=undefined)B(this.matches,new dp.sh.Match(A[2],A.index+A[0].indexOf(A[2]),&quot;attribute-value&quot;))}this.GetMatches(new RegExp(&quot;(&amp;lt;|&lt;)/*\\?*(?!\\!)|/*\\?*(&amp;gt;|&gt;)&quot;,&quot;gm&quot;),&quot;tag&quot;);_=new RegExp(&quot;(?:&amp;lt;|&lt;)/*\\?*\\s*([:\\w-.]+)&quot;,&quot;gm&quot;);while((A=_.exec(this.code))!=null)B(this.matches,new dp.sh.Match(A[1],A.index+A[0].indexOf(A[1]),&quot;tag-name&quot;))}
//}}}</pre>
</div>
<div title="TabAllTags" modifier="MPTW" created="201004041418" modified="201009151231">
<pre>&lt;&lt;allTags excludeLists&gt;&gt;
</pre>
</div>
<div title="TabMore" modifier="MPTW" created="201004041418" modified="201009151231">
<pre>&lt;&lt;tabs txtMoreTab &quot;Tags&quot; &quot;All Tags&quot; TabAllTags &quot;Miss&quot; &quot;Missing tiddlers&quot; TabMoreMissing &quot;Orph&quot; &quot;Orphaned tiddlers&quot; TabMoreOrphans &quot;Shad&quot; &quot;Shadowed tiddlers&quot; TabMoreShadowed&gt;&gt;
</pre>
</div>
<div title="TabTags" modifier="MPTW" created="201004041418" modified="201009151231">
<pre>&lt;&lt;allTags excludeLists [a-z]&gt;&gt;
</pre>
</div>
<div title="TabTimeline" modifier="Pascal" created="200801071156" modified="200801071235" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200801071235">
<pre>&lt;&lt;timeline &quot;&quot; 25&gt;&gt;</pre>
</div>
<div title="TaggerPlugin" modifier="Saq" created="200607191547" tags="lewcidExtension systemConfig" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200607191547" changecount="2">
<pre>/***
|''Name:''|~TaggerPlugin|
|''Version:''|1.0.1 (2006-06-01)|
|''Source:''|http://tw.lewcid.org//#TaggerPlugin|
|''Author:''|SaqImtiaz|
|''Description:''|Provides a drop down listing current tiddler tags, and allowing toggling of tags.|
|''Documentation:''|[[TaggerPluginDocumentation]]|
|''Source Code:''|[[TaggerPluginSource]]|
|''~TiddlyWiki:''|Version 2.0.8 or better|
***/
// /%
config.tagger={defaults:{label:&quot;Tags: &quot;,tooltip:&quot;Manage tiddler tags&quot;,taglist:&quot;true&quot;,excludeTags:&quot;&quot;,notags:&quot;tiddler has no tags&quot;,aretags:&quot;current tiddler tags:&quot;,toggletext:&quot;add tags:&quot;}};config.macros.tagger={};config.macros.tagger.arrow=(document.all?&quot;▼&quot;:&quot;▾&quot;);config.macros.tagger.handler=function(_1,_2,_3,_4,_5,_6){var _7=config.tagger.defaults;var _8=_5.parseParams(&quot;tagman&quot;,null,true);var _9=((_8[0].label)&amp;&amp;(_8[0].label[0])!=&quot;.&quot;)?_8[0].label[0]+this.arrow:_7.label+this.arrow;var _a=((_8[0].tooltip)&amp;&amp;(_8[0].tooltip[0])!=&quot;.&quot;)?_8[0].tooltip[0]:_7.tooltip;var _b=((_8[0].taglist)&amp;&amp;(_8[0].taglist[0])!=&quot;.&quot;)?_8[0].taglist[0]:_7.taglist;var _c=((_8[0].exclude)&amp;&amp;(_8[0].exclude[0])!=&quot;.&quot;)?(_8[0].exclude[0]).readBracketedList():_7.excludeTags.readBracketedList();if((_8[0].source)&amp;&amp;(_8[0].source[0])!=&quot;.&quot;){var _d=_8[0].source[0];}if(_d&amp;&amp;!store.getTiddler(_d)){return false;}var _e=function(e){if(!e){var e=window.event;}var _11=Popup.create(this);var _12=store.getTags();var _13=new Array();for(var i=0;i&lt;_12.length;i++){_13.push(_12[i][0]);}if(_d){var _15=store.getTiddler(_d);_13=_15.tags.sort();}var _16=_6.tags.sort();var _17=function(_18,_19,_1a){var sp=createTiddlyElement(createTiddlyElement(_11,&quot;li&quot;),&quot;span&quot;,null,&quot;tagger&quot;);var _1c=createTiddlyButton(sp,_18,_1a+&quot; '&quot;+_19+&quot;'&quot;,taggerOnToggle,&quot;button&quot;,&quot;toggleButton&quot;);_1c.setAttribute(&quot;tiddler&quot;,_6.title);_1c.setAttribute(&quot;tag&quot;,_19);insertSpacer(sp);if(window.createTagButton_orig_mptw){createTagButton_orig_mptw(sp,_19)}else{createTagButton(sp,_19);}};createTiddlyElement(_11,&quot;li&quot;,null,&quot;listTitle&quot;,(_6.tags.length==0?_7.notags:_7.aretags));for(var t=0;t&lt;_16.length;t++){_17(&quot;[x]&quot;,_16[t],&quot;remove tag &quot;);}createTiddlyElement(createTiddlyElement(_11,&quot;li&quot;),&quot;hr&quot;);if(_b!=&quot;false&quot;){createTiddlyElement(_11,&quot;li&quot;,null,&quot;listTitle&quot;,_7.toggletext);for(var i=0;i&lt;_13.length;i++){if(!_6.tags.contains(_13[i])&amp;&amp;!_c.contains(_13[i])){_17(&quot;[ ]&quot;,_13[i],&quot;add tag &quot;);}}createTiddlyElement(createTiddlyElement(_11,&quot;li&quot;),&quot;hr&quot;);}var _1f=createTiddlyButton(createTiddlyElement(_11,&quot;li&quot;),(&quot;Create new tag&quot;),null,taggerOnToggle);_1f.setAttribute(&quot;tiddler&quot;,_6.title);if(_d){_1f.setAttribute(&quot;source&quot;,_d);}Popup.show(_11,false);e.cancelBubble=true;if(e.stopPropagation){e.stopPropagation();}return (false);};createTiddlyButton(_1,_9,_a,_e,&quot;button&quot;,&quot;taggerDrpBtn&quot;);};window.taggerOnToggle=function(e){var tag=this.getAttribute(&quot;tag&quot;);var _22=this.getAttribute(&quot;tiddler&quot;);var _23=store.getTiddler(_22);if(!tag){var _24=prompt(&quot;Enter new tag:&quot;,&quot;&quot;);if(_24!=&quot;&quot;&amp;&amp;_24!=null){var tag=_24;if(this.getAttribute(&quot;source&quot;)){var _26=store.getTiddler(this.getAttribute(&quot;source&quot;));_26.tags.pushUnique(_24);}}else{return false;}}if(!_23||!_23.tags){store.saveTiddler(_22,_22,&quot;&quot;,config.options.txtUserName,new Date(),tag);}else{if(_23.tags.find(tag)==null){_23.tags.push(tag);}else{if(!_24){_23.tags.splice(_23.tags.find(tag),1);}}store.saveTiddler(_23.title,_23.title,_23.text,_23.modifier,_23.modified,_23.tags);}story.refreshTiddler(_22,null,true);if(config.options.chkAutoSave){saveChanges();}return false;};setStylesheet(&quot;.tagger a.button {font-weight: bold;display:inline; padding:0px;}\n&quot;+&quot;.tagger #toggleButton {padding-left:2px; padding-right:2px; margin-right:1px; font-size:110%;}\n&quot;+&quot;#nestedtagger {background:#2E5ADF; border: 1px solid #0331BF;}\n&quot;+&quot;.popup .listTitle {color:#000;}\n&quot;+&quot;&quot;,&quot;TaggerStyles&quot;);window.lewcidTiddlerSwapTag=function(_27,_28,_29){for(var i=0;i&lt;_27.tags.length;i++){if(_27.tags[i]==_28){_27.tags[i]=_29;return true;}}return false;};window.lewcidRenameTag=function(e){var tag=this.getAttribute(&quot;tag&quot;);var _2d=prompt(&quot;Rename tag '&quot;+tag+&quot;' to:&quot;,tag);if((_2d==tag)||(_2d==null)){return false;}if(store.tiddlerExists(_2d)){if(confirm(config.messages.overwriteWarning.format([_2d.toString()]))){story.closeTiddler(_2d,false,false);}else{return null;}}tagged=store.getTaggedTiddlers(tag);if(tagged.length!=0){for(var j=0;j&lt;tagged.length;j++){lewcidTiddlerSwapTag(tagged[j],tag,_2d);}}if(store.tiddlerExists(tag)){store.saveTiddler(tag,_2d);}if(document.getElementById(&quot;tiddler&quot;+tag)){var _2f=document.getElementById(story.idPrefix+tag);var _30=story.positionTiddler(_2f);var _31=document.getElementById(story.container);story.closeTiddler(tag,false,false);story.createTiddler(_31,_30,_2d,null);story.saveTiddler(_2d);}if(config.options.chkAutoSave){saveChanges();}return false;};window.onClickTag=function(e){if(!e){var e=window.event;}var _34=resolveTarget(e);var _35=(!isNested(_34));if((Popup.stack.length&gt;1)&amp;&amp;(_35==true)){Popup.removeFrom(1);}else{if(Popup.stack.length&gt;0&amp;&amp;_35==false){Popup.removeFrom(0);}}var _36=(_35==false)?&quot;popup&quot;:&quot;nestedtagger&quot;;var _37=createTiddlyElement(document.body,&quot;ol&quot;,_36,&quot;popup&quot;,null);Popup.stack.push({root:this,popup:_37});var tag=this.getAttribute(&quot;tag&quot;);var _39=this.getAttribute(&quot;tiddler&quot;);if(_37&amp;&amp;tag){var _3a=store.getTaggedTiddlers(tag);var _3b=[];var li,r;for(r=0;r&lt;_3a.length;r++){if(_3a[r].title!=_39){_3b.push(_3a[r].title);}}var _3d=config.views.wikified.tag;if(_3b.length&gt;0){var _3e=createTiddlyButton(createTiddlyElement(_37,&quot;li&quot;),_3d.openAllText.format([tag]),_3d.openAllTooltip,onClickTagOpenAll);_3e.setAttribute(&quot;tag&quot;,tag);createTiddlyElement(createTiddlyElement(_37,&quot;li&quot;),&quot;hr&quot;);for(r=0;r&lt;_3b.length;r++){createTiddlyLink(createTiddlyElement(_37,&quot;li&quot;),_3b[r],true);}}else{createTiddlyText(createTiddlyElement(_37,&quot;li&quot;,null,&quot;disabled&quot;),_3d.popupNone.format([tag]));}createTiddlyElement(createTiddlyElement(_37,&quot;li&quot;),&quot;hr&quot;);var h=createTiddlyLink(createTiddlyElement(_37,&quot;li&quot;),tag,false);createTiddlyText(h,_3d.openTag.format([tag]));createTiddlyElement(createTiddlyElement(_37,&quot;li&quot;),&quot;hr&quot;);var _40=createTiddlyButton(createTiddlyElement(_37,&quot;li&quot;),(&quot;Rename tag '&quot;+tag+&quot;'&quot;),null,lewcidRenameTag);_40.setAttribute(&quot;tag&quot;,tag);}Popup.show(_37,false);e.cancelBubble=true;if(e.stopPropagation){e.stopPropagation();}return (false);};if(!window.isNested){window.isNested=function(e){while(e!=null){var _42=document.getElementById(&quot;contentWrapper&quot;);if(_42==e){return true;}e=e.parentNode;}return false;};}config.shadowTiddlers.TaggerPluginDocumentation=&quot;The documentation is available [[here.|http://tw.lewcid.org/#TaggerPluginDocumentation]]&quot;;config.shadowTiddlers.TaggerPluginSource=&quot;The uncompressed source code is available [[here.|http://tw.lewcid.org/#TaggerPluginSource]]&quot;;
// %/</pre>
</div>
<div title="TagglyTaggingPlugin" modifier="MPTW" created="201004191432" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|TagglyTaggingPlugin|
|Description:|tagglyTagging macro is a replacement for the builtin tagging macro in your ViewTemplate|
|Version:|3.3.1 ($Rev: 9828 $)|
|Date:|$Date: 2009-06-03 21:38:41 +1000 (Wed, 03 Jun 2009) $|
|Source:|http://mptw.tiddlyspot.com/#TagglyTaggingPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!Notes
See http://mptw.tiddlyspot.com/#TagglyTagging
***/
//{{{

merge(String.prototype,{

	parseTagExpr: function(debug) {

		if (this.trim() == &quot;&quot;)
			return &quot;(true)&quot;;

		var anyLogicOp = /(!|&amp;&amp;|\|\||\(|\))/g;
		var singleLogicOp = /^(!|&amp;&amp;|\|\||\(|\))$/;

		var spaced = this.
			// because square brackets in templates are no good
			// this means you can use [(With Spaces)] instead of [[With Spaces]]
			replace(/\[\(/g,&quot; [[&quot;).
			replace(/\)\]/g,&quot;]] &quot;). 
			// space things out so we can use readBracketedList. tricky eh?
			replace(anyLogicOp,&quot; $1 &quot;);

		var expr = &quot;&quot;;

		var tokens = spaced.readBracketedList(false); // false means don't uniq the list. nice one JR!

		for (var i=0;i&lt;tokens.length;i++)
			if (tokens[i].match(singleLogicOp))
				expr += tokens[i];
			else
				expr += &quot;tiddler.tags.contains('%0')&quot;.format([tokens[i].replace(/'/,&quot;\\'&quot;)]); // fix single quote bug. still have round bracket bug i think

		if (debug)
			alert(expr);

		return '('+expr+')';
	}

});

merge(TiddlyWiki.prototype,{
	getTiddlersByTagExpr: function(tagExpr,sortField) {

		var result = [];

		var expr = tagExpr.parseTagExpr();

		store.forEachTiddler(function(title,tiddler) {
			if (eval(expr))
				result.push(tiddler);
		});

		if(!sortField)
			sortField = &quot;title&quot;;

		result.sort(function(a,b) {return a[sortField] &lt; b[sortField] ? -1 : (a[sortField] == b[sortField] ? 0 : +1);});
		
		return result;
	}
});

config.taggly = {

	// for translations
	lingo: {
		labels: {
			asc:        &quot;\u2191&quot;, // down arrow
			desc:       &quot;\u2193&quot;, // up arrow
			title:      &quot;title&quot;,
			modified:   &quot;modified&quot;,
			created:    &quot;created&quot;,
			show:       &quot;+&quot;,
			hide:       &quot;-&quot;,
			normal:     &quot;normal&quot;,
			group:      &quot;group&quot;,
			commas:     &quot;commas&quot;,
			sitemap:    &quot;sitemap&quot;,
			numCols:    &quot;cols\u00b1&quot;, // plus minus sign
			label:      &quot;Tagged as '%0':&quot;,
			exprLabel:  &quot;Matching tag expression '%0':&quot;,
			excerpts:   &quot;excerpts&quot;,
			descr:      &quot;descr&quot;,
			slices:     &quot;slices&quot;,
			contents:   &quot;contents&quot;,
			sliders:    &quot;sliders&quot;,
			noexcerpts: &quot;title only&quot;,
			noneFound:  &quot;(none)&quot;
		},

		tooltips: {
			title:      &quot;Click to sort by title&quot;,
			modified:   &quot;Click to sort by modified date&quot;,
			created:    &quot;Click to sort by created date&quot;,
			show:       &quot;Click to show tagging list&quot;,
			hide:       &quot;Click to hide tagging list&quot;,
			normal:     &quot;Click to show a normal ungrouped list&quot;,
			group:      &quot;Click to show list grouped by tag&quot;,
			sitemap:    &quot;Click to show a sitemap style list&quot;,
			commas:     &quot;Click to show a comma separated list&quot;,
			numCols:    &quot;Click to change number of columns&quot;,
			excerpts:   &quot;Click to show excerpts&quot;,
			descr:      &quot;Click to show the description slice&quot;,
			slices:     &quot;Click to show all slices&quot;,
			contents:   &quot;Click to show entire tiddler contents&quot;,
			sliders:    &quot;Click to show tiddler contents in sliders&quot;,
			noexcerpts: &quot;Click to show entire title only&quot;
		},

		tooDeepMessage: &quot;* //sitemap too deep...//&quot;
	},

	config: {
		showTaggingCounts: true,
		listOpts: {
			// the first one will be the default
			sortBy:     [&quot;title&quot;,&quot;modified&quot;,&quot;created&quot;],
			sortOrder:  [&quot;asc&quot;,&quot;desc&quot;],
			hideState:  [&quot;show&quot;,&quot;hide&quot;],
			listMode:   [&quot;normal&quot;,&quot;group&quot;,&quot;sitemap&quot;,&quot;commas&quot;],
			numCols:    [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;],
			excerpts:   [&quot;noexcerpts&quot;,&quot;excerpts&quot;,&quot;descr&quot;,&quot;slices&quot;,&quot;contents&quot;,&quot;sliders&quot;]
		},
		valuePrefix: &quot;taggly.&quot;,
		excludeTags: [&quot;excludeLists&quot;,&quot;excludeTagging&quot;],
		excerptSize: 50,
		excerptMarker: &quot;/%&quot;+&quot;%/&quot;,
		siteMapDepthLimit: 25
	},

	getTagglyOpt: function(title,opt) {
		var val = store.getValue(title,this.config.valuePrefix+opt);
		return val ? val : this.config.listOpts[opt][0];
	},

	setTagglyOpt: function(title,opt,value) {
		// create it silently if it doesn't exist
		if (!store.tiddlerExists(title)) {
			store.saveTiddler(title,title,config.views.editor.defaultText.format([title]),config.options.txtUserName,new Date(),&quot;&quot;);

			// &lt;&lt;tagglyTagging expr:&quot;...&quot;&gt;&gt; creates a tiddler to store its display settings
			// Make those tiddlers less noticeable by tagging as excludeSearch and excludeLists
			// Because we don't want to hide real tags, check that they aren't actually tags before doing so
			// Also tag them as tagglyExpression for manageability
			// (contributed by RA)
			if (!store.getTaggedTiddlers(title).length) {
				store.setTiddlerTag(title,true,&quot;excludeSearch&quot;);
				store.setTiddlerTag(title,true,&quot;excludeLists&quot;);
				store.setTiddlerTag(title,true,&quot;tagglyExpression&quot;);
			}
		}

		// if value is default then remove it to save space
		return store.setValue(title, this.config.valuePrefix+opt, value == this.config.listOpts[opt][0] ? null : value);
	},

	getNextValue: function(title,opt) {
		var current = this.getTagglyOpt(title,opt);
		var pos = this.config.listOpts[opt].indexOf(current);
		// supposed to automagically don't let cols cycle up past the number of items
		// currently broken in some situations, eg when using an expression
		// lets fix it later when we rewrite for jquery
		// the columns thing should be jquery table manipulation probably
		var limit = (opt == &quot;numCols&quot; ? store.getTaggedTiddlers(title).length : this.config.listOpts[opt].length);
		var newPos = (pos + 1) % limit;
		return this.config.listOpts[opt][newPos];
	},

	toggleTagglyOpt: function(title,opt) {
		var newVal = this.getNextValue(title,opt);
		this.setTagglyOpt(title,opt,newVal);
	}, 

	createListControl: function(place,title,type) {
		var lingo = config.taggly.lingo;
		var label;
		var tooltip;
		var onclick;

		if ((type == &quot;title&quot; || type == &quot;modified&quot; || type == &quot;created&quot;)) {
			// &quot;special&quot; controls. a little tricky. derived from sortOrder and sortBy
			label = lingo.labels[type];
			tooltip = lingo.tooltips[type];

			if (this.getTagglyOpt(title,&quot;sortBy&quot;) == type) {
				label += lingo.labels[this.getTagglyOpt(title,&quot;sortOrder&quot;)];
				onclick = function() {
					config.taggly.toggleTagglyOpt(title,&quot;sortOrder&quot;);
					return false;
				}
			}
			else {
				onclick = function() {
					config.taggly.setTagglyOpt(title,&quot;sortBy&quot;,type);
					config.taggly.setTagglyOpt(title,&quot;sortOrder&quot;,config.taggly.config.listOpts.sortOrder[0]);
					return false;
				}
			}
		}
		else {
			// &quot;regular&quot; controls, nice and simple
			label = lingo.labels[type == &quot;numCols&quot; ? type : this.getNextValue(title,type)];
			tooltip = lingo.tooltips[type == &quot;numCols&quot; ? type : this.getNextValue(title,type)];
			onclick = function() {
				config.taggly.toggleTagglyOpt(title,type);
				return false;
			}
		}

		// hide button because commas don't have columns
		if (!(this.getTagglyOpt(title,&quot;listMode&quot;) == &quot;commas&quot; &amp;&amp; type == &quot;numCols&quot;))
			createTiddlyButton(place,label,tooltip,onclick,type == &quot;hideState&quot; ? &quot;hidebutton&quot; : &quot;button&quot;);
	},

	makeColumns: function(orig,numCols) {
		var listSize = orig.length;
		var colSize = listSize/numCols;
		var remainder = listSize % numCols;

		var upperColsize = colSize;
		var lowerColsize = colSize;

		if (colSize != Math.floor(colSize)) {
			// it's not an exact fit so..
			upperColsize = Math.floor(colSize) + 1;
			lowerColsize = Math.floor(colSize);
		}

		var output = [];
		var c = 0;
		for (var j=0;j&lt;numCols;j++) {
			var singleCol = [];
			var thisSize = j &lt; remainder ? upperColsize : lowerColsize;
			for (var i=0;i&lt;thisSize;i++) 
				singleCol.push(orig[c++]);
			output.push(singleCol);
		}

		return output;
	},

	drawTable: function(place,columns,theClass) {
		var newTable = createTiddlyElement(place,&quot;table&quot;,null,theClass);
		var newTbody = createTiddlyElement(newTable,&quot;tbody&quot;);
		var newTr = createTiddlyElement(newTbody,&quot;tr&quot;);
		for (var j=0;j&lt;columns.length;j++) {
			var colOutput = &quot;&quot;;
			for (var i=0;i&lt;columns[j].length;i++) 
				colOutput += columns[j][i];
			var newTd = createTiddlyElement(newTr,&quot;td&quot;,null,&quot;tagglyTagging&quot;); // todo should not need this class
			wikify(colOutput,newTd);
		}
		return newTable;
	},

	createTagglyList: function(place,title,isTagExpr) {
		switch(this.getTagglyOpt(title,&quot;listMode&quot;)) {
			case &quot;group&quot;:  return this.createTagglyListGrouped(place,title,isTagExpr); break;
			case &quot;normal&quot;: return this.createTagglyListNormal(place,title,false,isTagExpr); break;
			case &quot;commas&quot;: return this.createTagglyListNormal(place,title,true,isTagExpr); break;
			case &quot;sitemap&quot;:return this.createTagglyListSiteMap(place,title,isTagExpr); break;
		}
	},

	getTaggingCount: function(title,isTagExpr) {
		// thanks to Doug Edmunds
		if (this.config.showTaggingCounts) {
			var tagCount = config.taggly.getTiddlers(title,'title',isTagExpr).length;
			if (tagCount &gt; 0)
				return &quot; (&quot;+tagCount+&quot;)&quot;;
		}
		return &quot;&quot;;
	},

	getTiddlers: function(titleOrExpr,sortBy,isTagExpr) {
		return isTagExpr ? store.getTiddlersByTagExpr(titleOrExpr,sortBy) : store.getTaggedTiddlers(titleOrExpr,sortBy);
	},

	getExcerpt: function(inTiddlerTitle,title,indent) {
		if (!indent)
			indent = 1;

		var displayMode = this.getTagglyOpt(inTiddlerTitle,&quot;excerpts&quot;);
		var t = store.getTiddler(title);

		if (t &amp;&amp; displayMode == &quot;excerpts&quot;) {
			var text = t.text.replace(/\n/,&quot; &quot;);
			var marker = text.indexOf(this.config.excerptMarker);
			if (marker != -1) {
				return &quot; {{excerpt{&lt;nowiki&gt;&quot; + text.substr(0,marker) + &quot;&lt;/nowiki&gt;}}}&quot;;
			}
			else if (text.length &lt; this.config.excerptSize) {
				return &quot; {{excerpt{&lt;nowiki&gt;&quot; + t.text + &quot;&lt;/nowiki&gt;}}}&quot;;
			}
			else {
				return &quot; {{excerpt{&lt;nowiki&gt;&quot; + t.text.substr(0,this.config.excerptSize) + &quot;...&quot; + &quot;&lt;/nowiki&gt;}}}&quot;;
			}
		}
		else if (t &amp;&amp; displayMode == &quot;contents&quot;) {
			return &quot;\n{{contents indent&quot;+indent+&quot;{\n&quot; + t.text + &quot;\n}}}&quot;;
		}
		else if (t &amp;&amp; displayMode == &quot;sliders&quot;) {
			return &quot;&lt;slider slide&gt;\n{{contents{\n&quot; + t.text + &quot;\n}}}\n&lt;/slider&gt;&quot;;
		}
		else if (t &amp;&amp; displayMode == &quot;descr&quot;) {
			var descr = store.getTiddlerSlice(title,'Description');
			return descr ? &quot; {{excerpt{&quot; + descr  + &quot;}}}&quot; : &quot;&quot;;
		}
		else if (t &amp;&amp; displayMode == &quot;slices&quot;) {
			var result = &quot;&quot;;
			var slices = store.calcAllSlices(title);
			for (var s in slices)
				result += &quot;|%0|&lt;nowiki&gt;%1&lt;/nowiki&gt;|\n&quot;.format([s,slices[s]]);
			return result ? &quot;\n{{excerpt excerptIndent{\n&quot; + result  + &quot;}}}&quot; : &quot;&quot;;
		}
		return &quot;&quot;;
	},

	notHidden: function(t,inTiddler) {
		if (typeof t == &quot;string&quot;) 
			t = store.getTiddler(t);
		return (!t || !t.tags.containsAny(this.config.excludeTags) ||
				(inTiddler &amp;&amp; this.config.excludeTags.contains(inTiddler)));
	},

	// this is for normal and commas mode
	createTagglyListNormal: function(place,title,useCommas,isTagExpr) {

		var list = config.taggly.getTiddlers(title,this.getTagglyOpt(title,&quot;sortBy&quot;),isTagExpr);

		if (this.getTagglyOpt(title,&quot;sortOrder&quot;) == &quot;desc&quot;)
			list = list.reverse();

		var output = [];
		var first = true;
		for (var i=0;i&lt;list.length;i++) {
			if (this.notHidden(list[i],title)) {
				var countString = this.getTaggingCount(list[i].title);
				var excerpt = this.getExcerpt(title,list[i].title);
				if (useCommas)
					output.push((first ? &quot;&quot; : &quot;, &quot;) + &quot;[[&quot; + list[i].title + &quot;]]&quot; + countString + excerpt);
				else
					output.push(&quot;*[[&quot; + list[i].title + &quot;]]&quot; + countString + excerpt + &quot;\n&quot;);

				first = false;
			}
		}

		return this.drawTable(place,
			this.makeColumns(output,useCommas ? 1 : parseInt(this.getTagglyOpt(title,&quot;numCols&quot;))),
			useCommas ? &quot;commas&quot; : &quot;normal&quot;);
	},

	// this is for the &quot;grouped&quot; mode
	createTagglyListGrouped: function(place,title,isTagExpr) {
		var sortBy = this.getTagglyOpt(title,&quot;sortBy&quot;);
		var sortOrder = this.getTagglyOpt(title,&quot;sortOrder&quot;);

		var list = config.taggly.getTiddlers(title,sortBy,isTagExpr);

		if (sortOrder == &quot;desc&quot;)
			list = list.reverse();

		var leftOvers = []
		for (var i=0;i&lt;list.length;i++)
			leftOvers.push(list[i].title);

		var allTagsHolder = {};
		for (var i=0;i&lt;list.length;i++) {
			for (var j=0;j&lt;list[i].tags.length;j++) {

				if (list[i].tags[j] != title) { // not this tiddler

					if (this.notHidden(list[i].tags[j],title)) {

						if (!allTagsHolder[list[i].tags[j]])
							allTagsHolder[list[i].tags[j]] = &quot;&quot;;

						if (this.notHidden(list[i],title)) {
							allTagsHolder[list[i].tags[j]] += &quot;**[[&quot;+list[i].title+&quot;]]&quot;
										+ this.getTaggingCount(list[i].title) + this.getExcerpt(title,list[i].title) + &quot;\n&quot;;

							leftOvers.setItem(list[i].title,-1); // remove from leftovers. at the end it will contain the leftovers

						}
					}
				}
			}
		}

		var allTags = [];
		for (var t in allTagsHolder)
			allTags.push(t);

		var sortHelper = function(a,b) {
			if (a == b) return 0;
			if (a &lt; b) return -1;
			return 1;
		};

		allTags.sort(function(a,b) {
			var tidA = store.getTiddler(a);
			var tidB = store.getTiddler(b);
			if (sortBy == &quot;title&quot;) return sortHelper(a,b);
			else if (!tidA &amp;&amp; !tidB) return 0;
			else if (!tidA) return -1;
			else if (!tidB) return +1;
			else return sortHelper(tidA[sortBy],tidB[sortBy]);
		});

		var leftOverOutput = &quot;&quot;;
		for (var i=0;i&lt;leftOvers.length;i++)
			if (this.notHidden(leftOvers[i],title))
				leftOverOutput += &quot;*[[&quot;+leftOvers[i]+&quot;]]&quot; + this.getTaggingCount(leftOvers[i]) + this.getExcerpt(title,leftOvers[i]) + &quot;\n&quot;;

		var output = [];

		if (sortOrder == &quot;desc&quot;)
			allTags.reverse();
		else if (leftOverOutput != &quot;&quot;)
			// leftovers first...
			output.push(leftOverOutput);

		for (var i=0;i&lt;allTags.length;i++)
			if (allTagsHolder[allTags[i]] != &quot;&quot;)
				output.push(&quot;*[[&quot;+allTags[i]+&quot;]]&quot; + this.getTaggingCount(allTags[i]) + this.getExcerpt(title,allTags[i]) + &quot;\n&quot; + allTagsHolder[allTags[i]]);

		if (sortOrder == &quot;desc&quot; &amp;&amp; leftOverOutput != &quot;&quot;)
			// leftovers last...
			output.push(leftOverOutput);

		return this.drawTable(place,
				this.makeColumns(output,parseInt(this.getTagglyOpt(title,&quot;numCols&quot;))),
				&quot;grouped&quot;);

	},

	// used to build site map
	treeTraverse: function(title,depth,sortBy,sortOrder,isTagExpr) {

		var list = config.taggly.getTiddlers(title,sortBy,isTagExpr);

		if (sortOrder == &quot;desc&quot;)
			list.reverse();

		var indent = &quot;&quot;;
		for (var j=0;j&lt;depth;j++)
			indent += &quot;*&quot;

		var childOutput = &quot;&quot;;

		if (depth &gt; this.config.siteMapDepthLimit)
			childOutput += indent + this.lingo.tooDeepMessage + &quot;\n&quot;;
		else
			for (var i=0;i&lt;list.length;i++)
				if (list[i].title != title)
					if (this.notHidden(list[i].title,this.config.inTiddler))
						childOutput += this.treeTraverse(list[i].title,depth+1,sortBy,sortOrder,false);

		if (depth == 0)
			return childOutput;
		else
			return indent + &quot;[[&quot;+title+&quot;]]&quot; + this.getTaggingCount(title) + this.getExcerpt(this.config.inTiddler,title,depth) + &quot;\n&quot; + childOutput;
	},

	// this if for the site map mode
	createTagglyListSiteMap: function(place,title,isTagExpr) {
		this.config.inTiddler = title; // nasty. should pass it in to traverse probably
		var output = this.treeTraverse(title,0,this.getTagglyOpt(title,&quot;sortBy&quot;),this.getTagglyOpt(title,&quot;sortOrder&quot;),isTagExpr);
		return this.drawTable(place,
				this.makeColumns(output.split(/(?=^\*\[)/m),parseInt(this.getTagglyOpt(title,&quot;numCols&quot;))), // regexp magic
				&quot;sitemap&quot;
				);
	},

	macros: {
		tagglyTagging: {
			handler: function (place,macroName,params,wikifier,paramString,tiddler) {
				var parsedParams = paramString.parseParams(&quot;tag&quot;,null,true);
				var refreshContainer = createTiddlyElement(place,&quot;div&quot;);

				// do some refresh magic to make it keep the list fresh - thanks Saq
				refreshContainer.setAttribute(&quot;refresh&quot;,&quot;macro&quot;);
				refreshContainer.setAttribute(&quot;macroName&quot;,macroName);

				var tag = getParam(parsedParams,&quot;tag&quot;);
				var expr = getParam(parsedParams,&quot;expr&quot;);

				if (expr) {
					refreshContainer.setAttribute(&quot;isTagExpr&quot;,&quot;true&quot;);
					refreshContainer.setAttribute(&quot;title&quot;,expr);
					refreshContainer.setAttribute(&quot;showEmpty&quot;,&quot;true&quot;);
				}
				else {
					refreshContainer.setAttribute(&quot;isTagExpr&quot;,&quot;false&quot;);
					if (tag) {
        				refreshContainer.setAttribute(&quot;title&quot;,tag);
						refreshContainer.setAttribute(&quot;showEmpty&quot;,&quot;true&quot;);
					}
					else {
        				refreshContainer.setAttribute(&quot;title&quot;,tiddler.title);
						refreshContainer.setAttribute(&quot;showEmpty&quot;,&quot;false&quot;);
					}
				}
				this.refresh(refreshContainer);
			},

			refresh: function(place) {
				var title = place.getAttribute(&quot;title&quot;);
				var isTagExpr = place.getAttribute(&quot;isTagExpr&quot;) == &quot;true&quot;;
				var showEmpty = place.getAttribute(&quot;showEmpty&quot;) == &quot;true&quot;;
				removeChildren(place);
				addClass(place,&quot;tagglyTagging&quot;);
				var countFound = config.taggly.getTiddlers(title,'title',isTagExpr).length
				if (countFound &gt; 0 || showEmpty) {
					var lingo = config.taggly.lingo;
					config.taggly.createListControl(place,title,&quot;hideState&quot;);
					if (config.taggly.getTagglyOpt(title,&quot;hideState&quot;) == &quot;show&quot;) {
						createTiddlyElement(place,&quot;span&quot;,null,&quot;tagglyLabel&quot;,
								isTagExpr ? lingo.labels.exprLabel.format([title]) : lingo.labels.label.format([title]));
						config.taggly.createListControl(place,title,&quot;title&quot;);
						config.taggly.createListControl(place,title,&quot;modified&quot;);
						config.taggly.createListControl(place,title,&quot;created&quot;);
						config.taggly.createListControl(place,title,&quot;listMode&quot;);
						config.taggly.createListControl(place,title,&quot;excerpts&quot;);
						config.taggly.createListControl(place,title,&quot;numCols&quot;);
						config.taggly.createTagglyList(place,title,isTagExpr);
						if (countFound == 0 &amp;&amp; showEmpty)
							createTiddlyElement(place,&quot;div&quot;,null,&quot;tagglyNoneFound&quot;,lingo.labels.noneFound);
					}
				}
			}
		}
	},

	// todo fix these up a bit
	styles: [
&quot;/*{{{*/&quot;,
&quot;/* created by TagglyTaggingPlugin */&quot;,
&quot;.tagglyTagging { padding-top:0.5em; }&quot;,
&quot;.tagglyTagging li.listTitle { display:none; }&quot;,
&quot;.tagglyTagging ul {&quot;,
&quot;	margin-top:0px; padding-top:0.5em; padding-left:2em;&quot;,
&quot;	margin-bottom:0px; padding-bottom:0px;&quot;,
&quot;}&quot;,
&quot;.tagglyTagging { vertical-align: top; margin:0px; padding:0px; }&quot;,
&quot;.tagglyTagging table { margin:0px; padding:0px; }&quot;,
&quot;.tagglyTagging .button { visibility:hidden; margin-left:3px; margin-right:3px; }&quot;,
&quot;.tagglyTagging .button, .tagglyTagging .hidebutton {&quot;,
&quot;	color:[[ColorPalette::TertiaryLight]]; font-size:90%;&quot;,
&quot;	border:0px; padding-left:0.3em;padding-right:0.3em;&quot;,
&quot;}&quot;,
&quot;.tagglyTagging .button:hover, .hidebutton:hover, &quot;,
&quot;.tagglyTagging .button:active, .hidebutton:active  {&quot;,
&quot;	border:0px; background:[[ColorPalette::TertiaryPale]]; color:[[ColorPalette::TertiaryDark]];&quot;,
&quot;}&quot;,
&quot;.selected .tagglyTagging .button { visibility:visible; }&quot;,
&quot;.tagglyTagging .hidebutton { color:[[ColorPalette::Background]]; }&quot;,
&quot;.selected .tagglyTagging .hidebutton { color:[[ColorPalette::TertiaryLight]] }&quot;,
&quot;.tagglyLabel { color:[[ColorPalette::TertiaryMid]]; font-size:90%; }&quot;,
&quot;.tagglyTagging ul {padding-top:0px; padding-bottom:0.5em; margin-left:1em; }&quot;,
&quot;.tagglyTagging ul ul {list-style-type:disc; margin-left:-1em;}&quot;,
&quot;.tagglyTagging ul ul li {margin-left:0.5em; }&quot;,
&quot;.editLabel { font-size:90%; padding-top:0.5em; }&quot;,
&quot;.tagglyTagging .commas { padding-left:1.8em; }&quot;,
&quot;/* not technically tagglytagging but will put them here anyway */&quot;,
&quot;.tagglyTagged li.listTitle { display:none; }&quot;,
&quot;.tagglyTagged li { display: inline; font-size:90%; }&quot;,
&quot;.tagglyTagged ul { margin:0px; padding:0px; }&quot;,
&quot;.excerpt { color:[[ColorPalette::TertiaryDark]]; }&quot;,
&quot;.excerptIndent { margin-left:4em; }&quot;,
&quot;div.tagglyTagging table,&quot;,
&quot;div.tagglyTagging table tr,&quot;,
&quot;td.tagglyTagging&quot;,
&quot; {border-style:none!important; }&quot;,
&quot;.tagglyTagging .contents { border-bottom:2px solid [[ColorPalette::TertiaryPale]]; padding:0 1em 1em 0.5em;&quot;,
&quot;  margin-bottom:0.5em; }&quot;,
&quot;.tagglyTagging .indent1  { margin-left:3em;  }&quot;,
&quot;.tagglyTagging .indent2  { margin-left:4em;  }&quot;,
&quot;.tagglyTagging .indent3  { margin-left:5em;  }&quot;,
&quot;.tagglyTagging .indent4  { margin-left:6em;  }&quot;,
&quot;.tagglyTagging .indent5  { margin-left:7em;  }&quot;,
&quot;.tagglyTagging .indent6  { margin-left:8em;  }&quot;,
&quot;.tagglyTagging .indent7  { margin-left:9em;  }&quot;,
&quot;.tagglyTagging .indent8  { margin-left:10em; }&quot;,
&quot;.tagglyTagging .indent9  { margin-left:11em; }&quot;,
&quot;.tagglyTagging .indent10 { margin-left:12em; }&quot;,
&quot;.tagglyNoneFound { margin-left:2em; color:[[ColorPalette::TertiaryMid]]; font-size:90%; font-style:italic; }&quot;,
&quot;/*}}}*/&quot;,
		&quot;&quot;].join(&quot;\n&quot;),

	init: function() {
		merge(config.macros,this.macros);
		config.shadowTiddlers[&quot;TagglyTaggingStyles&quot;] = this.styles;
		store.addNotification(&quot;TagglyTaggingStyles&quot;,refreshStyles);
	}
};

config.taggly.init();

//}}}

/***
InlineSlidersPlugin
By Saq Imtiaz
http://tw.lewcid.org/sandbox/#InlineSlidersPlugin

// syntax adjusted to not clash with NestedSlidersPlugin
// added + syntax to start open instead of closed

***/
//{{{
config.formatters.unshift( {
	name: &quot;inlinesliders&quot;,
	// match: &quot;\\+\\+\\+\\+|\\&lt;slider&quot;,
	match: &quot;\\&lt;slider&quot;,
	// lookaheadRegExp: /(?:\+\+\+\+|&lt;slider) (.*?)(?:&gt;?)\n((?:.|\n)*?)\n(?:====|&lt;\/slider&gt;)/mg,
	lookaheadRegExp: /(?:&lt;slider)(\+?) (.*?)(?:&gt;)\n((?:.|\n)*?)\n(?:&lt;\/slider&gt;)/mg,
	handler: function(w) {
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source)
		if(lookaheadMatch &amp;&amp; lookaheadMatch.index == w.matchStart ) {
			var btn = createTiddlyButton(w.output,lookaheadMatch[2] + &quot; &quot;+&quot;\u00BB&quot;,lookaheadMatch[2],this.onClickSlider,&quot;button sliderButton&quot;);
			var panel = createTiddlyElement(w.output,&quot;div&quot;,null,&quot;sliderPanel&quot;);
			panel.style.display = (lookaheadMatch[1] == '+' ? &quot;block&quot; : &quot;none&quot;);
			wikify(lookaheadMatch[3],panel);
			w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
		}
   },
   onClickSlider : function(e) {
		if(!e) var e = window.event;
		var n = this.nextSibling;
		n.style.display = (n.style.display==&quot;none&quot;) ? &quot;block&quot; : &quot;none&quot;;
		return false;
	}
});

//}}}

</pre>
</div>
<div title="TagsTreePlugin" modifier="Pascal" created="200801041056" modified="200801071022" tags="Tools systemConfig VisualTW systemConfigDisable" label="TagsTree" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200801071022" changecount="3">
<pre>/***
|''Name:''|TagsTreePlugin|
|''Description:''|Displays tags hierachy as a tree of tagged tiddlers.&lt;br&gt;Can be used to create dynamic outline navigation.|
|''Version:''|1.0.1|
|''Date:''|Jan 04,2008|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0|
!Demo
On the plugin [[homepage|http://visualtw.ouvaton.org/VisualTW.html]] :
*Try to tag some &lt;&lt;newTiddler&gt;&gt; with a tag displayed in the menu and edit MainMenu.
*Look at some tags like [[Plugins]] or [[menu]].
!Installation
#import the plugin,
#save and reload,
#optionally, edit TagsTreeStyleSheet.
! Usage
{{{&lt;&lt;tagsTree&gt;&gt;}}} macro accepts the following //optional// parameters.
|!#|!parameter|!description|!by default|
|1|{{{root}}}|Uses {{{root}}} tag as tree root|- In a //tiddler// content or template : uses the tiddler as root tag.&lt;br&gt;- In the //page// content or template (by ex MainMenu) : displays all untagged tags.|
|2|{{{excludeTag}}}|Excludes all such tagged tiddlers from the tree|Uses default excludeLists tag|
|3|{{{level}}}|Expands nodes until level {{{level}}}.&lt;br&gt;Value {{{0}}} hides expand/collapse buttons.|Nodes are collapsed on first level|
|4|{{{depth}}}|Hierachy depth|6 levels depth (H1 to H6 header styles)|
|5|{{{sortField}}}|Alternate sort field. By example : &quot;index&quot;.|Sorts tags and tiddlers alphabetically (on their title)|
|6|{{{labelField}}}|Alertnate label field. By example : &quot;label&quot;.|Displays tiddler's title|

!Useful addons
*[[FieldsEditorPlugin]] : //create//, //edit//, //view// and //delete// commands in toolbar &lt;&lt;toolbar fields&gt;&gt;.
*[[TaggerPlugin]] : Provides a drop down listing current tiddler tags, and allowing toggling of tags.
!Advanced Users
You can change the global defaults for TagsTreePlugin, like default {{{level}}} value or level styles, by editing or overriding the first config.macros.tagsTree attributes below.
!Code
***/
//{{{
config.macros.tagsTree = {
	expand : &quot;+&quot;,
	collapse : &quot;–&quot;,
	depth : 6,
	level : 1,
	sortField : &quot;&quot;,	
	labelField : &quot;&quot;,
	styles : [&quot;h1&quot;,&quot;h2&quot;,&quot;h3&quot;,&quot;h4&quot;,&quot;h5&quot;,&quot;h6&quot;],
	trees : {}
}

config.macros.tagsTree.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var root = params[0] ? params[0] : (tiddler ? tiddler.title : null);
	var excludeTag = params[1] ? params[1] : &quot;excludeTagsTree&quot;;
	var level = params[2] ? params[2] : config.macros.tagsTree.level;
	var depth = params[3] ? params[3] : config.macros.tagsTree.depth;
	var sortField = params[4] ? params[4] : config.macros.tagsTree.sortField;
	var labelField = params[5] ? params[5] : config.macros.tagsTree.labelField;
	var showButtons = (level&gt;0);
	var id = config.macros.tagsTree.getId(place);
	if (config.macros.tagsTree.trees[id]==undefined) config.macros.tagsTree.trees[id]={};
	config.macros.tagsTree.createSubTree(place,id,root,excludeTag,[],level&gt;0 ? level : 1,depth, sortField, labelField,showButtons);
}

config.macros.tagsTree.createSubTree = function(place, id, root, excludeTag, ancestors, level, depth, sortField, labelField,showButtons){
	var childNodes = root ? this.getChildNodes(root, ancestors) : this.getRootTags(excludeTag);
	var isOpen = (level&gt;0) || (!showButtons);
	if (root &amp;&amp; this.trees[id][root]!=undefined) isOpen = this.trees[id][root]; 
	if (root &amp;&amp; ancestors.length) {
		var t = store.getTiddler(root);
		if (childNodes.length &amp;&amp; depth&gt;0) {
			var wrapper = createTiddlyElement(place , this.styles[Math.min(Math.max(ancestors.length,1),6)-1],null,&quot;branch&quot;);
			if (showButtons) {
				b = createTiddlyButton(wrapper, isOpen ? config.macros.tagsTree.collapse : config.macros.tagsTree.expand, null, config.macros.tagsTree.onClick);
				b.setAttribute(&quot;treeId&quot;,id);
				b.setAttribute(&quot;tiddler&quot;,root);					
			}
			createTiddlyText(createTiddlyLink(wrapper, root),t&amp;&amp;labelField ? t.fields[labelField] ? t.fields[labelField] : root : root);
		}
		else 
			createTiddlyText(createTiddlyLink(place, root,false,&quot;leaf&quot;),t&amp;&amp;labelField ? t.fields[labelField] ? t.fields[labelField] : root : root);
	}
	if (childNodes.length &amp;&amp; depth) {
		var d = createTiddlyElement(place,&quot;div&quot;,null,&quot;subtree&quot;);
		d.style.display= isOpen ? &quot;block&quot; : &quot;none&quot;;
		if (sortField)
			childNodes.sort(function(a, b){
				var fa=a.fields[sortField];
				var fb=b.fields[sortField];
				return (fa==undefined &amp;&amp; fb==undefined) ? a.title &lt; b.title ? -1 : a.title &gt; b.title ? 1 : 0 : (fa==undefined &amp;&amp; fb!=undefined) ? 1 :(fa!=undefined &amp;&amp; fb==undefined) ? -1 : fa &lt; fb ? -1 : fa &gt; fb ? 1 : 0;
			})
		for (var cpt=0; cpt&lt;childNodes.length; cpt++)
			this.createSubTree(d, id, childNodes[cpt].title, excludeTag, ancestors.concat(root), level-1, depth-1, sortField, labelField, showButtons);	
	}	
}

config.macros.tagsTree.onClick = function(e){
	var id = this.getAttribute(&quot;treeId&quot;);
	var tiddler = this.getAttribute(&quot;tiddler&quot;);	
	var n = this.parentNode.nextSibling;
	var isOpen = n.style.display != &quot;none&quot;;
	if(config.options.chkAnimate &amp;&amp; anim &amp;&amp; typeof Slider == &quot;function&quot;)
		anim.startAnimating(new Slider(n,!isOpen,null,&quot;none&quot;));
	else
		n.style.display = isOpen ? &quot;none&quot; : &quot;block&quot;;
	this.firstChild.nodeValue = isOpen ? config.macros.tagsTree.expand : config.macros.tagsTree.collapse;
	config.macros.tagsTree.trees[id][tiddler]=!isOpen;
	return false;
}

config.macros.tagsTree.getChildNodes = function(root ,ancestors){
	var childs = store.getTaggedTiddlers(root);
	var result = new Array();
	for (var cpt=0; cpt&lt;childs.length; cpt++)
		if (childs[cpt].title!=root &amp;&amp; ancestors.indexOf(childs[cpt].title)==-1) result.push(childs[cpt]);
	return result;
}

config.macros.tagsTree.getRootTags = function(excludeTag){
	var tags = store.getTags(excludeTag);
	tags.sort(function(a,b) {return a[0].toLowerCase() &lt; b[0].toLowerCase() ? -1 : (a[0].toLowerCase() == b[0].toLowerCase() ? 0 : +1);});
	var result = new Array();
	for (var cpt=0; cpt&lt;tags.length; cpt++) {
		var t = store.getTiddler(tags[cpt][0]);
		if (!t || t.tags.length==0) result.push(t ? t : {title:tags[cpt][0],fields:{}});
	}
	return result;
}

config.macros.tagsTree.getId = function(element){
	while (!element.id &amp;&amp; element.parentNode) element=element.parentNode;
	return element.id ? element.id : &quot;&lt;html&gt;&quot;;
}

config.shadowTiddlers.TagsTreeStyleSheet = &quot;/*{{{*/\n&quot;;
config.shadowTiddlers.TagsTreeStyleSheet +=&quot;.leaf, .subtree {display:block; margin-left : 0.5em}\n&quot;;
config.shadowTiddlers.TagsTreeStyleSheet +=&quot;.subtree {margin-bottom:0.5em}\n&quot;;
config.shadowTiddlers.TagsTreeStyleSheet +=&quot;#mainMenu {text-align:left}\n&quot;;
config.shadowTiddlers.TagsTreeStyleSheet +=&quot;.branch .button {border:1px solid #DDD; color:#AAA;font-size:9px;padding:0 2px;margin-right:0.3em;vertical-align:middle;text-align:center;}\n&quot;;
config.shadowTiddlers.TagsTreeStyleSheet +=&quot;/*}}}*/&quot;;

store.addNotification(&quot;TagsTreeStyleSheet&quot;, refreshStyles); 

config.shadowTiddlers.MainMenu=&quot;&lt;&lt;tagsTree&gt;&gt;&quot;

config.shadowTiddlers.PageTemplate = config.shadowTiddlers.PageTemplate.replace(/id='mainMenu' refresh='content' /,&quot;id='mainMenu' refresh='content' force='true' &quot;)

//}}}</pre>
</div>
<div title="TestCode" modifier="YourName" created="201103071950" modified="201103080013" tags="code" changecount="3">
<pre>&lt;code C++&gt;
 int main(int argc, char*argv[]) {
    puts(&quot;hi!\n&quot;);
} 

&lt;/code&gt;
</pre>
</div>
<div title="The AWK Programming Language" modifier="Jonny Gerold" created="201008102044" modified="201008102044" tags="Books" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201008102044">
<pre>Type the text for 'The AWK Programming Language'</pre>
</div>
<div title="The C Programming Language" modifier="Jonny Gerold" created="201012140356" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201012140356">
<pre>* [[Chapter 1 - A tutorial Introduction|CH1-A_Tutorial_Introduction]]</pre>
</div>
<div title="The C++ Programming Language" modifier="Jonny Gerold" created="201008102044" modified="201010310238" tags="Books" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201010310238">
<pre>* Part 0: Introduction
**	[[Ch 1 Notes to the Reader|CPP_PL:Introduction:1 Notes to the Reader]]
**	[[Ch 2 A Tour of C++|CPP_PL:Introduction:2 A Tour of C++]]
**	[[Ch 3 A Tour of the Standard Library|CPP_PL:Introduction:3 A Tour of the Standard Library]]
* Part 1: Basic Facilities
**	[[Ch 4 Types and Declarations|CPP_PL:Basic_Facilities:4 Types and Declarations]]
**	[[Ch 5 Pointers, Arrays, and Structures|CPP_PL:Basic_Facilities:5 Pointers, Arrays, and Structures]]</pre>
</div>
<div title="TiddlerReference" modifier="StephenWilliams" created="201103090820" modified="201103090826" tags="TiddlyWiki" changecount="3">
<pre>http://www.tiddlywiki.com/

http://tiddlywiki.org/wiki/URL_Commands
http://tiddlywiki.org/wiki/TiddlyWiki_Markup
http://visualtw.ouvaton.org/VisualTW.html

http://tiddlertoddler.tiddlyspot.com/
http://blogoehlert.typepad.com/eclippings/files/eclippingstiddlywiki.html
http://www.tiddlytools.com/

This TiddlyWiki started with this distribution: http://mptw.tiddlyspot.com/

TiddlyWikis are very cool.  The most amazing are [[ASciencePad|http://math.chapman.edu/~jipsen/asciencepad/asciencepad.html]] and [[TiddlyMath|http://math.chapman.edu/~jipsen/tiddly/tiddlymath.html]], especially when you consider that math publishing via web technologies was in the dark ages just a few years ago.  Even more amazing, all of these work on Android Firefox, especially including the Motorola Mobility Atrix using the full-size screen/keyboard/touchpad &quot;dock&quot;.</pre>
</div>
<div title="TiddlersBarPlugin" modifier="StephenWilliams" created="200708071235" modified="201103080644" tags="VisualTW systemConfig Tools systemConfigDisable" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200801181510" label="TiddlersBar" changecount="2">
<pre>/***
|''Name:''|TiddlersBarPlugin|
|''Description:''|A bar to switch between tiddlers through tabs (like browser tabs bar).|
|''Version:''|1.2.5|
|''Date:''|Jan 18,2008|
|''Source:''|http://visualtw.ouvaton.org/VisualTW.html|
|''Author:''|Pascal Collin|
|''License:''|[[BSD open source license|License]]|
|''~CoreVersion:''|2.1.0|
|''Browser:''|Firefox 2.0; InternetExplorer 6.0, others|
!Demos
On [[homepage|http://visualtw.ouvaton.org/VisualTW.html]], open several tiddlers to use the tabs bar.
!Installation
#import this tiddler from [[homepage|http://visualtw.ouvaton.org/VisualTW.html]] (tagged as systemConfig)
#save and reload
#''if you're using a custom [[PageTemplate]]'', add {{{&lt;div id='tiddlersBar' refresh='none' ondblclick='config.macros.tiddlersBar.onTiddlersBarAction(event)'&gt;&lt;/div&gt;}}} before {{{&lt;div id='tiddlerDisplay'&gt;&lt;/div&gt;}}}
#optionally, adjust StyleSheetTiddlersBar
!Tips
*Doubleclick on the tiddlers bar (where there is no tab) create a new tiddler.
*Tabs include a button to close {{{x}}} or save {{{!}}} their tiddler.
*By default, click on the current tab close all others tiddlers.
!Configuration options 
&lt;&lt;option chkDisableTabsBar&gt;&gt; Disable the tabs bar (to print, by example).
&lt;&lt;option chkHideTabsBarWhenSingleTab &gt;&gt; Automatically hide the tabs bar when only one tiddler is displayed. 
&lt;&lt;option txtSelectedTiddlerTabButton&gt;&gt; ''selected'' tab command button.
&lt;&lt;option txtPreviousTabKey&gt;&gt; previous tab access key.
&lt;&lt;option txtNextTabKey&gt;&gt; next tab access key.
!Code
***/
//{{{
config.options.chkDisableTabsBar = config.options.chkDisableTabsBar ? config.options.chkDisableTabsBar : false;
config.options.chkHideTabsBarWhenSingleTab  = config.options.chkHideTabsBarWhenSingleTab  ? config.options.chkHideTabsBarWhenSingleTab  : false;
config.options.txtSelectedTiddlerTabButton = config.options.txtSelectedTiddlerTabButton ? config.options.txtSelectedTiddlerTabButton : &quot;closeOthers&quot;;
config.options.txtPreviousTabKey = config.options.txtPreviousTabKey ? config.options.txtPreviousTabKey : &quot;&quot;;
config.options.txtNextTabKey = config.options.txtNextTabKey ? config.options.txtNextTabKey : &quot;&quot;;
config.macros.tiddlersBar = {
	tooltip : &quot;see &quot;,
	tooltipClose : &quot;click here to close this tab&quot;,
	tooltipSave : &quot;click here to save this tab&quot;,
	promptRename : &quot;Enter tiddler new name&quot;,
	currentTiddler : &quot;&quot;,
	previousState : false,
	previousKey : config.options.txtPreviousTabKey,
	nextKey : config.options.txtNextTabKey,	
	tabsAnimationSource : null, //use document.getElementById(&quot;tiddlerDisplay&quot;) if you need animation on tab switching.
	handler: function(place,macroName,params) {
		var previous = null;
		if (config.macros.tiddlersBar.isShown())
			story.forEachTiddler(function(title,e){
				if (title==config.macros.tiddlersBar.currentTiddler){
					var d = createTiddlyElement(null,&quot;span&quot;,null,&quot;tab tabSelected&quot;);
					config.macros.tiddlersBar.createActiveTabButton(d,title);
					if (previous &amp;&amp; config.macros.tiddlersBar.previousKey) previous.setAttribute(&quot;accessKey&quot;,config.macros.tiddlersBar.nextKey);
					previous = &quot;active&quot;;
				}
				else {
					var d = createTiddlyElement(place,&quot;span&quot;,null,&quot;tab tabUnselected&quot;);
					var btn = createTiddlyButton(d,title,config.macros.tiddlersBar.tooltip + title,config.macros.tiddlersBar.onSelectTab);
					btn.setAttribute(&quot;tiddler&quot;, title);
					if (previous==&quot;active&quot; &amp;&amp; config.macros.tiddlersBar.nextKey) btn.setAttribute(&quot;accessKey&quot;,config.macros.tiddlersBar.previousKey);
					previous=btn;
				}
				var isDirty =story.isDirty(title);
				var c = createTiddlyButton(d,isDirty ?&quot;!&quot;:&quot;x&quot;,isDirty?config.macros.tiddlersBar.tooltipSave:config.macros.tiddlersBar.tooltipClose, isDirty ? config.macros.tiddlersBar.onTabSave : config.macros.tiddlersBar.onTabClose,&quot;tabButton&quot;);
				c.setAttribute(&quot;tiddler&quot;, title);
				if (place.childNodes) {
					place.insertBefore(document.createTextNode(&quot; &quot;),place.firstChild); // to allow break line here when many tiddlers are open
					place.insertBefore(d,place.firstChild); 
				}
				else place.appendChild(d);
			})
	}, 
	refresh: function(place,params){
		removeChildren(place);
		config.macros.tiddlersBar.handler(place,&quot;tiddlersBar&quot;,params);
		if (config.macros.tiddlersBar.previousState!=config.macros.tiddlersBar.isShown()) {
			story.refreshAllTiddlers();
			if (config.macros.tiddlersBar.previousState) story.forEachTiddler(function(t,e){e.style.display=&quot;&quot;;});
			config.macros.tiddlersBar.previousState = !config.macros.tiddlersBar.previousState;
		}
	},
	isShown : function(){
		if (config.options.chkDisableTabsBar) return false;
		if (!config.options.chkHideTabsBarWhenSingleTab) return true;
		var cpt=0;
		story.forEachTiddler(function(){cpt++});
		return (cpt&gt;1);
	},
	selectNextTab : function(){  //used when the current tab is closed (to select another tab)
		var previous=&quot;&quot;;
		story.forEachTiddler(function(title){
			if (!config.macros.tiddlersBar.currentTiddler) {
				story.displayTiddler(null,title);
				return;
			}
			if (title==config.macros.tiddlersBar.currentTiddler) {
				if (previous) {
					story.displayTiddler(null,previous);
					return;
				}
				else config.macros.tiddlersBar.currentTiddler=&quot;&quot;; 	// so next tab will be selected
			}
			else previous=title;
			});		
	},
	onSelectTab : function(e){
		var t = this.getAttribute(&quot;tiddler&quot;);
		if (t) story.displayTiddler(null,t);
		return false;
	},
	onTabClose : function(e){
		var t = this.getAttribute(&quot;tiddler&quot;);
		if (t) {
			if(story.hasChanges(t) &amp;&amp; !readOnly) {
				if(!confirm(config.commands.cancelTiddler.warning.format([t])))
				return false;
			}
			story.closeTiddler(t);
		}
		return false;
	},
	onTabSave : function(e) {
		var t = this.getAttribute(&quot;tiddler&quot;);
		if (!e) e=window.event;
		if (t) config.commands.saveTiddler.handler(e,null,t);
		return false;
	},
	onSelectedTabButtonClick : function(event,src,title) {
		var t = this.getAttribute(&quot;tiddler&quot;);
		if (!event) event=window.event;
		if (t &amp;&amp; config.options.txtSelectedTiddlerTabButton &amp;&amp; config.commands[config.options.txtSelectedTiddlerTabButton])
			config.commands[config.options.txtSelectedTiddlerTabButton].handler(event, src, t);
		return false;
	},
	onTiddlersBarAction: function(event) {
		var source = event.target ? event.target.id : event.srcElement.id; // FF uses target and IE uses srcElement;
		if (source==&quot;tiddlersBar&quot;) story.displayTiddler(null,'New Tiddler',DEFAULT_EDIT_TEMPLATE,false,null,null);
	},
	createActiveTabButton : function(place,title) {
		if (config.options.txtSelectedTiddlerTabButton &amp;&amp; config.commands[config.options.txtSelectedTiddlerTabButton]) {
			var btn = createTiddlyButton(place, title, config.commands[config.options.txtSelectedTiddlerTabButton].tooltip ,config.macros.tiddlersBar.onSelectedTabButtonClick);
			btn.setAttribute(&quot;tiddler&quot;, title);
		}
		else
			createTiddlyText(place,title);
	}
}

story.coreCloseTiddler = story.coreCloseTiddler? story.coreCloseTiddler : story.closeTiddler;
story.coreDisplayTiddler = story.coreDisplayTiddler ? story.coreDisplayTiddler : story.displayTiddler;

story.closeTiddler = function(title,animate,unused) {
	if (title==config.macros.tiddlersBar.currentTiddler)
		config.macros.tiddlersBar.selectNextTab();
	story.coreCloseTiddler(title,false,unused); //disable animation to get it closed before calling tiddlersBar.refresh
	var e=document.getElementById(&quot;tiddlersBar&quot;);
	if (e) config.macros.tiddlersBar.refresh(e,null);
}

story.displayTiddler = function(srcElement,tiddler,template,animate,unused,customFields,toggle){
	story.coreDisplayTiddler(config.macros.tiddlersBar.tabsAnimationSource,tiddler,template,animate,unused,customFields,toggle);
	var title = (tiddler instanceof Tiddler)? tiddler.title : tiddler;  
	if (config.macros.tiddlersBar.isShown()) {
		story.forEachTiddler(function(t,e){
			if (t!=title) e.style.display=&quot;none&quot;;
			else e.style.display=&quot;&quot;;
		})
		config.macros.tiddlersBar.currentTiddler=title;
	}
	var e=document.getElementById(&quot;tiddlersBar&quot;);
	if (e) config.macros.tiddlersBar.refresh(e,null);
}

var coreRefreshPageTemplate = coreRefreshPageTemplate ? coreRefreshPageTemplate : refreshPageTemplate;
refreshPageTemplate = function(title) {
	coreRefreshPageTemplate(title);
	if (config.macros.tiddlersBar) config.macros.tiddlersBar.refresh(document.getElementById(&quot;tiddlersBar&quot;));
}

ensureVisible=function (e) {return 0} //disable bottom scrolling (not useful now)

config.shadowTiddlers.StyleSheetTiddlersBar = &quot;/*{{{*/\n&quot;;
config.shadowTiddlers.StyleSheetTiddlersBar += &quot;#tiddlersBar .button {border:0}\n&quot;;
config.shadowTiddlers.StyleSheetTiddlersBar += &quot;#tiddlersBar .tab {white-space:nowrap}\n&quot;;
config.shadowTiddlers.StyleSheetTiddlersBar += &quot;#tiddlersBar {padding : 1em 0.5em 2px 0.5em}\n&quot;;
config.shadowTiddlers.StyleSheetTiddlersBar += &quot;.tabUnselected .tabButton, .tabSelected .tabButton {padding : 0 2px 0 2px; margin: 0 0 0 4px;}\n&quot;;
config.shadowTiddlers.StyleSheetTiddlersBar += &quot;.tiddler, .tabContents {border:1px [[ColorPalette::TertiaryPale]] solid;}\n&quot;;
config.shadowTiddlers.StyleSheetTiddlersBar +=&quot;/*}}}*/&quot;;
store.addNotification(&quot;StyleSheetTiddlersBar&quot;, refreshStyles);

config.refreshers.none = function(){return true;}
config.shadowTiddlers.PageTemplate=config.shadowTiddlers.PageTemplate.replace(/&lt;div id='tiddlerDisplay'&gt;&lt;\/div&gt;/m,&quot;&lt;div id='tiddlersBar' refresh='none' ondblclick='config.macros.tiddlersBar.onTiddlersBarAction(event)'&gt;&lt;/div&gt;\n&lt;div id='tiddlerDisplay'&gt;&lt;/div&gt;&quot;);

//}}}</pre>
</div>
<div title="TiddlyWiki" modifier="StephenWilliams" created="201103090821" changecount="1">
<pre>See TiddlerReference</pre>
</div>
<div title="ToggleTagPlugin" modifier="MPTW" created="201004041418" modified="201009151231" tags="systemConfig">
<pre>/***
|Name:|ToggleTagPlugin|
|Description:|Makes a checkbox which toggles a tag in a tiddler|
|Version:|3.1.0 ($Rev: 4907 $)|
|Date:|$Date: 2008-05-13 03:15:46 +1000 (Tue, 13 May 2008) $|
|Source:|http://mptw.tiddlyspot.com/#ToggleTagPlugin|
|Author:|Simon Baird &lt;simon.baird@gmail.com&gt;|
|License:|http://mptw.tiddlyspot.com/#TheBSDLicense|
!!Usage
{{{&lt;&lt;toggleTag }}}//{{{TagName TiddlerName LabelText}}}//{{{&gt;&gt;}}}
* TagName - the tag to be toggled, default value &quot;checked&quot;
* TiddlerName - the tiddler to toggle the tag in, default value the current tiddler
* LabelText - the text (gets wikified) to put next to the check box, default value is '{{{[[TagName]]}}}' or '{{{[[TagName]] [[TiddlerName]]}}}'
(If a parameter is '.' then the default will be used)
* TouchMod flag - if non empty then touch the tiddlers mod date. Note, can set config.toggleTagAlwaysTouchModDate to always touch mod date
!!Examples
|Code|Description|Example|h
|{{{&lt;&lt;toggleTag&gt;&gt;}}}|Toggles the default tag (checked) in this tiddler|&lt;&lt;toggleTag&gt;&gt;|
|{{{&lt;&lt;toggleTag TagName&gt;&gt;}}}|Toggles the TagName tag in this tiddler|&lt;&lt;toggleTag TagName&gt;&gt;|
|{{{&lt;&lt;toggleTag TagName TiddlerName&gt;&gt;}}}|Toggles the TagName tag in the TiddlerName tiddler|&lt;&lt;toggleTag TagName TiddlerName&gt;&gt;|
|{{{&lt;&lt;toggleTag TagName TiddlerName 'click me'&gt;&gt;}}}|Same but with custom label|&lt;&lt;toggleTag TagName TiddlerName 'click me'&gt;&gt;|
|{{{&lt;&lt;toggleTag . . 'click me'&gt;&gt;}}}|dot means use default value|&lt;&lt;toggleTag . . 'click me'&gt;&gt;|
!!Notes
* If TiddlerName doesn't exist it will be silently created
* Set label to '-' to specify no label
* See also http://mgtd-alpha.tiddlyspot.com/#ToggleTag2
!!Known issues
* Doesn't smoothly handle the case where you toggle a tag in a tiddler that is current open for editing
* Should convert to use named params
***/
//{{{

if (config.toggleTagAlwaysTouchModDate == undefined) config.toggleTagAlwaysTouchModDate = false;

merge(config.macros,{

	toggleTag: {

		createIfRequired: true,
		shortLabel: &quot;[[%0]]&quot;,
		longLabel: &quot;[[%0]] [[%1]]&quot;,

		handler: function(place,macroName,params,wikifier,paramString,tiddler) {
			var tiddlerTitle = tiddler ? tiddler.title : '';
			var tag   = (params[0] &amp;&amp; params[0] != '.') ? params[0] : &quot;checked&quot;;
			var title = (params[1] &amp;&amp; params[1] != '.') ? params[1] : tiddlerTitle;
			var defaultLabel = (title == tiddlerTitle ? this.shortLabel : this.longLabel);
			var label = (params[2] &amp;&amp; params[2] != '.') ? params[2] : defaultLabel;
			var touchMod = (params[3] &amp;&amp; params[3] != '.') ? params[3] : &quot;&quot;;
			label = (label == '-' ? '' : label); // dash means no label
			var theTiddler = (title == tiddlerTitle ? tiddler : store.getTiddler(title));
			var cb = createTiddlyCheckbox(place, label.format([tag,title]), theTiddler &amp;&amp; theTiddler.isTagged(tag), function(e) {
				if (!store.tiddlerExists(title)) {
					if (config.macros.toggleTag.createIfRequired) {
						var content = store.getTiddlerText(title); // just in case it's a shadow
						store.saveTiddler(title,title,content?content:&quot;&quot;,config.options.txtUserName,new Date(),null);
					}
					else 
						return false;
				}
				if ((touchMod != &quot;&quot; || config.toggleTagAlwaysTouchModDate) &amp;&amp; theTiddler)
						theTiddler.modified = new Date();
				store.setTiddlerTag(title,this.checked,tag);
				return true;
			});
		}
	}
});

//}}}

</pre>
</div>
<div title="Version Control" modifier="Jonny Gerold" created="201008102033" modified="201008102038" server.type="file" server.host="dl.getdropbox.com/u/52078/Notes/Notes.html" server.page.revision="201008102038">
<pre>* [[Git]]</pre>
</div>
<div title="Wysiwyg" modifier="Pascal" created="200801041225" tags="Plugins" index="1" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200801041225">
<pre></pre>
</div>
<div title="WysiwygDemo" modifier="Pascal" created="200712111657" modified="200712141201" tags="Demos" label="Wysiwyg" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712141201">
<pre>&lt;html&gt;&lt;p&gt;Use the tiddler's toolbar to edit this text with :&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;EasyEditPlugin : click on &lt;b&gt;write&lt;/b&gt; button.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;FCKeditorPlugin : click on &lt;b&gt;wysiwyg&lt;/b&gt; button.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;ExternalizePlugin : click on &lt;b&gt;externalize&lt;/b&gt; button&lt;span style=&quot;font-weight: bold;&quot;&gt;.&amp;nbsp; &lt;/span&gt;&lt;span style=&quot;color: rgb(255, 102, 0); font-weight: bold;&quot;&gt;This requires :&lt;/span&gt;&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Firefox &lt;br&gt;&lt;/span&gt;&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;&quot;it's all text!&quot;&lt;/span&gt; Firefox extension and configuration (editor and hotkey)&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;[[plugin	configuration|ExternalizePlugin]], enter &lt;span style=&quot;font-style: italic;&quot;&gt;hotkey&lt;/span&gt; and check &lt;span style=&quot;font-style: italic;&quot;&gt;file Extensions&lt;/span&gt; is starting with .html (for this demo)&lt;/p&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;Standard &lt;span style=&quot;font-weight: bold;&quot;&gt;edit &lt;/span&gt;button to look at the resulting code.&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;By example, you can use the following formats :&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;Bullets list&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;Orderer list&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;Font &lt;font color=&quot;#ff0000&quot;&gt;color&lt;/font&gt;, &lt;font face=&quot;Times New Roman, serif&quot;&gt;name&lt;/font&gt;,	&lt;font style=&quot;font-size: 15pt;&quot; size=&quot;4&quot;&gt;size&lt;/font&gt;, ...&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;Bold&lt;/b&gt;, &lt;i&gt;italic&lt;/i&gt;, &lt;u&gt;underline&lt;/u&gt;, &lt;strike&gt;strikethrough&lt;/strike&gt;&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;[[Links|EasyEditPlugin]]&lt;/p&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/html&gt;</pre>
</div>
<div title="WysiwygPlugin" modifier="Pascal" created="200712112144" modified="200712112158" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712112158">
<pre>renamed FCKeditorPlugin</pre>
</div>
<div title="lewcidExtension" modifier="Pascal" created="200712101052" tags="excludeLists" server.type="file" server.host="http://visualtw.ouvaton.org/VisualTW.html" server.page.revision="200712101052">
<pre></pre>
</div>
<div title="systemConfig" modifier="MPTW" created="201009151231" modified="201009151231" taggly.excerpts="descr" taggly.sortby="created" taggly.sortorder="desc">
<pre></pre>
</div>
</div>
<!--POST-STOREAREA-->
<!--POST-BODY-START-->
<!--POST-BODY-END-->
<script id="jsArea" type="text/javascript">
//<![CDATA[
//
// Please note:
//
// * This code is designed to be readable but for compactness it only includes brief comments. You can see fuller comments
//   in the project Subversion repository at http://svn.tiddlywiki.org/Trunk/core/
//
// * You should never need to modify this source code directly. TiddlyWiki is carefully designed to allow deep customisation
//   without changing the core code. Please consult the development group at http://groups.google.com/group/TiddlyWikiDev
//

//--
//-- Configuration repository
//--

// Miscellaneous options
var config = {
	numRssItems: 20, // Number of items in the RSS feed
	animDuration: 400, // Duration of UI animations in milliseconds
	cascadeFast: 20, // Speed for cascade animations (higher == slower)
	cascadeSlow: 60, // Speed for EasterEgg cascade animations
	cascadeDepth: 5, // Depth of cascade animation
	locale: "en" // W3C language tag
};

// Hashmap of alternative parsers for the wikifier
config.parsers = {};

// Adaptors
config.adaptors = {};
config.defaultAdaptor = null;

// Backstage tasks
config.tasks = {};

// Annotations
config.annotations = {};

// Custom fields to be automatically added to new tiddlers
config.defaultCustomFields = {};

// Messages
config.messages = {
	messageClose: {},
	dates: {},
	tiddlerPopup: {}
};

// Options that can be set in the options panel and/or cookies
config.options = {
	chkRegExpSearch: false,
	chkCaseSensitiveSearch: false,
	chkIncrementalSearch: true,
	chkAnimate: true,
	chkSaveBackups: true,
	chkAutoSave: false,
	chkGenerateAnRssFeed: false,
	chkSaveEmptyTemplate: false,
	chkOpenInNewWindow: true,
	chkToggleLinks: false,
	chkHttpReadOnly: true,
	chkForceMinorUpdate: false,
	chkConfirmDelete: true,
	chkInsertTabs: false,
	chkUsePreForStorage: true, // Whether to use <pre> format for storage
	chkDisplayInstrumentation: false,
	txtBackupFolder: "",
	txtEditorFocus: "text",
	txtMainTab: "tabTimeline",
	txtMoreTab: "moreTabAll",
	txtMaxEditRows: "30",
	txtFileSystemCharSet: "UTF-8",
	txtTheme: ""
	};
config.optionsDesc = {};

config.optionsSource = {};

// Default tiddler templates
var DEFAULT_VIEW_TEMPLATE = 1;
var DEFAULT_EDIT_TEMPLATE = 2;
config.tiddlerTemplates = {
	1: "ViewTemplate",
	2: "EditTemplate"
};

// More messages (rather a legacy layout that should not really be like this)
config.views = {
	wikified: {
		tag: {}
	},
	editor: {
		tagChooser: {}
	}
};

// Backstage tasks
config.backstageTasks = ["save","sync","importTask","tweak","upgrade","plugins"];

// Extensions
config.extensions = {};

// Macros; each has a 'handler' member that is inserted later
config.macros = {
	today: {},
	version: {},
	search: {sizeTextbox: 15},
	tiddler: {},
	tag: {},
	tags: {},
	tagging: {},
	timeline: {},
	allTags: {},
	list: {
		all: {},
		missing: {},
		orphans: {},
		shadowed: {},
		touched: {},
		filter: {}
	},
	closeAll: {},
	permaview: {},
	saveChanges: {},
	slider: {},
	option: {},
	options: {},
	newTiddler: {},
	newJournal: {},
	tabs: {},
	gradient: {},
	message: {},
	view: {defaultView: "text"},
	edit: {},
	tagChooser: {},
	toolbar: {},
	plugins: {},
	refreshDisplay: {},
	importTiddlers: {},
	upgrade: {
		source: "http://www.tiddlywiki.com/upgrade/",
		backupExtension: "pre.core.upgrade"
	},
	sync: {},
	annotations: {}
};

// Commands supported by the toolbar macro
config.commands = {
	closeTiddler: {},
	closeOthers: {},
	editTiddler: {},
	saveTiddler: {hideReadOnly: true},
	cancelTiddler: {},
	deleteTiddler: {hideReadOnly: true},
	permalink: {},
	references: {type: "popup"},
	jump: {type: "popup"},
	syncing: {type: "popup"},
	fields: {type: "popup"}
};

// Browser detection... In a very few places, there's nothing else for it but to know what browser we're using.
config.userAgent = navigator.userAgent.toLowerCase();
config.browser = {
	isIE: config.userAgent.indexOf("msie") != -1 && config.userAgent.indexOf("opera") == -1,
	isGecko: navigator.product == "Gecko" && config.userAgent.indexOf("WebKit") == -1,
	ieVersion: /MSIE (\d.\d)/i.exec(config.userAgent), // config.browser.ieVersion[1], if it exists, will be the IE version string, eg "6.0"
	isSafari: config.userAgent.indexOf("applewebkit") != -1,
	isBadSafari: !((new RegExp("[\u0150\u0170]","g")).test("\u0150")),
	firefoxDate: /gecko\/(\d{8})/i.exec(config.userAgent), // config.browser.firefoxDate[1], if it exists, will be Firefox release date as "YYYYMMDD"
	isOpera: config.userAgent.indexOf("opera") != -1,
	isLinux: config.userAgent.indexOf("linux") != -1,
	isUnix: config.userAgent.indexOf("x11") != -1,
	isMac: config.userAgent.indexOf("mac") != -1,
	isWindows: config.userAgent.indexOf("win") != -1
};

// Control of macro parameter evaluation
config.evaluateMacroParameters = "all";

// Basic regular expressions
config.textPrimitives = {
	upperLetter: "[A-Z\u00c0-\u00de\u0150\u0170]",
	lowerLetter: "[a-z0-9_\\-\u00df-\u00ff\u0151\u0171]",
	anyLetter:   "[A-Za-z0-9_\\-\u00c0-\u00de\u00df-\u00ff\u0150\u0170\u0151\u0171]",
	anyLetterStrict: "[A-Za-z0-9\u00c0-\u00de\u00df-\u00ff\u0150\u0170\u0151\u0171]"
};
if(config.browser.isBadSafari) {
	config.textPrimitives = {
		upperLetter: "[A-Z\u00c0-\u00de]",
		lowerLetter: "[a-z0-9_\\-\u00df-\u00ff]",
		anyLetter:   "[A-Za-z0-9_\\-\u00c0-\u00de\u00df-\u00ff]",
		anyLetterStrict: "[A-Za-z0-9\u00c0-\u00de\u00df-\u00ff]"
	};
}
config.textPrimitives.sliceSeparator = "::";
config.textPrimitives.sectionSeparator = "##";
config.textPrimitives.urlPattern = "(?:file|http|https|mailto|ftp|irc|news|data):[^\\s'\"]+(?:/|\\b)";
config.textPrimitives.unWikiLink = "~";
config.textPrimitives.wikiLink = "(?:(?:" + config.textPrimitives.upperLetter + "+" +
	config.textPrimitives.lowerLetter + "+" +
	config.textPrimitives.upperLetter +
	config.textPrimitives.anyLetter + "*)|(?:" +
	config.textPrimitives.upperLetter + "{2,}" +
	config.textPrimitives.lowerLetter + "+))";

config.textPrimitives.cssLookahead = "(?:(" + config.textPrimitives.anyLetter + "+)\\(([^\\)\\|\\n]+)(?:\\):))|(?:(" + config.textPrimitives.anyLetter + "+):([^;\\|\\n]+);)";
config.textPrimitives.cssLookaheadRegExp = new RegExp(config.textPrimitives.cssLookahead,"mg");

config.textPrimitives.brackettedLink = "\\[\\[([^\\]]+)\\]\\]";
config.textPrimitives.titledBrackettedLink = "\\[\\[([^\\[\\]\\|]+)\\|([^\\[\\]\\|]+)\\]\\]";
config.textPrimitives.tiddlerForcedLinkRegExp = new RegExp("(?:" + config.textPrimitives.titledBrackettedLink + ")|(?:" +
	config.textPrimitives.brackettedLink + ")|(?:" +
	config.textPrimitives.urlPattern + ")","mg");
config.textPrimitives.tiddlerAnyLinkRegExp = new RegExp("("+ config.textPrimitives.wikiLink + ")|(?:" +
	config.textPrimitives.titledBrackettedLink + ")|(?:" +
	config.textPrimitives.brackettedLink + ")|(?:" +
	config.textPrimitives.urlPattern + ")","mg");

config.glyphs = {
	browsers: [
		function() {return config.browser.isIE;},
		function() {return true;}
	],
	currBrowser: null,
	codes: {
		downTriangle: ["\u25BC","\u25BE"],
		downArrow: ["\u2193","\u2193"],
		bentArrowLeft: ["\u2190","\u21A9"],
		bentArrowRight: ["\u2192","\u21AA"]
	}
};

//--
//-- Shadow tiddlers
//--

config.shadowTiddlers = {
	StyleSheet: "",
	MarkupPreHead: "",
	MarkupPostHead: "",
	MarkupPreBody: "",
	MarkupPostBody: "",
	TabTimeline: '<<timeline>>',
	TabAll: '<<list all>>',
	TabTags: '<<allTags excludeLists>>',
	TabMoreMissing: '<<list missing>>',
	TabMoreOrphans: '<<list orphans>>',
	TabMoreShadowed: '<<list shadowed>>',
	AdvancedOptions: '<<options>>',
	PluginManager: '<<plugins>>',
	ToolbarCommands: '|~ViewToolbar|closeTiddler closeOthers +editTiddler > fields syncing permalink references jump|\n|~EditToolbar|+saveTiddler -cancelTiddler deleteTiddler|',
	WindowTitle: '<<tiddler SiteTitle>> - <<tiddler SiteSubtitle>>'
};

//--
//-- Translateable strings
//--

// Strings in "double quotes" should be translated; strings in 'single quotes' should be left alone

merge(config.options,{
	txtUserName: "YourName"});

merge(config.tasks,{
	save: {text: "save", tooltip: "Save your changes to this TiddlyWiki", action: saveChanges},
	sync: {text: "sync", tooltip: "Synchronise changes with other TiddlyWiki files and servers", content: '<<sync>>'},
	importTask: {text: "import", tooltip: "Import tiddlers and plugins from other TiddlyWiki files and servers", content: '<<importTiddlers>>'},
	tweak: {text: "tweak", tooltip: "Tweak the appearance and behaviour of TiddlyWiki", content: '<<options>>'},
	upgrade: {text: "upgrade", tooltip: "Upgrade TiddlyWiki core code", content: '<<upgrade>>'},
	plugins: {text: "plugins", tooltip: "Manage installed plugins", content: '<<plugins>>'}
});

// Options that can be set in the options panel and/or cookies
merge(config.optionsDesc,{
	txtUserName: "Username for signing your edits",
	chkRegExpSearch: "Enable regular expressions for searches",
	chkCaseSensitiveSearch: "Case-sensitive searching",
	chkIncrementalSearch: "Incremental key-by-key searching",
	chkAnimate: "Enable animations",
	chkSaveBackups: "Keep backup file when saving changes",
	chkAutoSave: "Automatically save changes",
	chkGenerateAnRssFeed: "Generate an RSS feed when saving changes",
	chkSaveEmptyTemplate: "Generate an empty template when saving changes",
	chkOpenInNewWindow: "Open external links in a new window",
	chkToggleLinks: "Clicking on links to open tiddlers causes them to close",
	chkHttpReadOnly: "Hide editing features when viewed over HTTP",
	chkForceMinorUpdate: "Don't update modifier username and date when editing tiddlers",
	chkConfirmDelete: "Require confirmation before deleting tiddlers",
	chkInsertTabs: "Use the tab key to insert tab characters instead of moving between fields",
	txtBackupFolder: "Name of folder to use for backups",
	txtMaxEditRows: "Maximum number of rows in edit boxes",
	txtTheme: "Name of the theme to use",
	txtFileSystemCharSet: "Default character set for saving changes (Firefox/Mozilla only)"});

merge(config.messages,{
	customConfigError: "Problems were encountered loading plugins. See PluginManager for details",
	pluginError: "Error: %0",
	pluginDisabled: "Not executed because disabled via 'systemConfigDisable' tag",
	pluginForced: "Executed because forced via 'systemConfigForce' tag",
	pluginVersionError: "Not executed because this plugin needs a newer version of TiddlyWiki",
	nothingSelected: "Nothing is selected. You must select one or more items first",
	savedSnapshotError: "It appears that this TiddlyWiki has been incorrectly saved. Please see http://www.tiddlywiki.com/#Download for details",
	subtitleUnknown: "(unknown)",
	undefinedTiddlerToolTip: "The tiddler '%0' doesn't yet exist",
	shadowedTiddlerToolTip: "The tiddler '%0' doesn't yet exist, but has a pre-defined shadow value",
	tiddlerLinkTooltip: "%0 - %1, %2",
	externalLinkTooltip: "External link to %0",
	noTags: "There are no tagged tiddlers",
	notFileUrlError: "You need to save this TiddlyWiki to a file before you can save changes",
	cantSaveError: "It's not possible to save changes. Possible reasons include:\n- your browser doesn't support saving (Firefox, Internet Explorer, Safari and Opera all work if properly configured)\n- the pathname to your TiddlyWiki file contains illegal characters\n- the TiddlyWiki HTML file has been moved or renamed",
	invalidFileError: "The original file '%0' does not appear to be a valid TiddlyWiki",
	backupSaved: "Backup saved",
	backupFailed: "Failed to save backup file",
	rssSaved: "RSS feed saved",
	rssFailed: "Failed to save RSS feed file",
	emptySaved: "Empty template saved",
	emptyFailed: "Failed to save empty template file",
	mainSaved: "Main TiddlyWiki file saved",
	mainFailed: "Failed to save main TiddlyWiki file. Your changes have not been saved",
	macroError: "Error in macro <<\%0>>",
	macroErrorDetails: "Error while executing macro <<\%0>>:\n%1",
	missingMacro: "No such macro",
	overwriteWarning: "A tiddler named '%0' already exists. Choose OK to overwrite it",
	unsavedChangesWarning: "WARNING! There are unsaved changes in TiddlyWiki\n\nChoose OK to save\nChoose CANCEL to discard",
	confirmExit: "--------------------------------\n\nThere are unsaved changes in TiddlyWiki. If you continue you will lose those changes\n\n--------------------------------",
	saveInstructions: "SaveChanges",
	unsupportedTWFormat: "Unsupported TiddlyWiki format '%0'",
	tiddlerSaveError: "Error when saving tiddler '%0'",
	tiddlerLoadError: "Error when loading tiddler '%0'",
	wrongSaveFormat: "Cannot save with storage format '%0'. Using standard format for save.",
	invalidFieldName: "Invalid field name %0",
	fieldCannotBeChanged: "Field '%0' cannot be changed",
	loadingMissingTiddler: "Attempting to retrieve the tiddler '%0' from the '%1' server at:\n\n'%2' in the workspace '%3'",
	upgradeDone: "The upgrade to version %0 is now complete\n\nClick 'OK' to reload the newly upgraded TiddlyWiki",
	invalidCookie: "Invalid cookie '%0'"});

merge(config.messages.messageClose,{
	text: "close",
	tooltip: "close this message area"});

config.messages.backstage = {
	open: {text: "backstage", tooltip: "Open the backstage area to perform authoring and editing tasks"},
	close: {text: "close", tooltip: "Close the backstage area"},
	prompt: "backstage: ",
	decal: {
		edit: {text: "edit", tooltip: "Edit the tiddler '%0'"}
	}
};

config.messages.listView = {
	tiddlerTooltip: "Click for the full text of this tiddler",
	previewUnavailable: "(preview not available)"
};

config.messages.dates.months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December"];
config.messages.dates.days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
config.messages.dates.shortMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
config.messages.dates.shortDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
// suffixes for dates, eg "1st","2nd","3rd"..."30th","31st"
config.messages.dates.daySuffixes = ["st","nd","rd","th","th","th","th","th","th","th",
		"th","th","th","th","th","th","th","th","th","th",
		"st","nd","rd","th","th","th","th","th","th","th",
		"st"];
config.messages.dates.am = "am";
config.messages.dates.pm = "pm";

merge(config.messages.tiddlerPopup,{
	});

merge(config.views.wikified.tag,{
	labelNoTags: "no tags",
	labelTags: "tags: ",
	openTag: "Open tag '%0'",
	tooltip: "Show tiddlers tagged with '%0'",
	openAllText: "Open all",
	openAllTooltip: "Open all of these tiddlers",
	popupNone: "No other tiddlers tagged with '%0'"});

merge(config.views.wikified,{
	defaultText: "The tiddler '%0' doesn't yet exist. Double-click to create it",
	defaultModifier: "(missing)",
	shadowModifier: "(built-in shadow tiddler)",
	dateFormat: "DD MMM YYYY",
	createdPrompt: "created"});

merge(config.views.editor,{
	tagPrompt: "Type tags separated with spaces, [[use double square brackets]] if necessary, or add existing",
	defaultText: "Type the text for '%0'"});

merge(config.views.editor.tagChooser,{
	text: "tags",
	tooltip: "Choose existing tags to add to this tiddler",
	popupNone: "There are no tags defined",
	tagTooltip: "Add the tag '%0'"});

merge(config.messages,{
	sizeTemplates:
		[
		{unit: 1024*1024*1024, template: "%0\u00a0GB"},
		{unit: 1024*1024, template: "%0\u00a0MB"},
		{unit: 1024, template: "%0\u00a0KB"},
		{unit: 1, template: "%0\u00a0B"}
		]});

merge(config.macros.search,{
	label: "search",
	prompt: "Search this TiddlyWiki",
	accessKey: "F",
	successMsg: "%0 tiddlers found matching %1",
	failureMsg: "No tiddlers found matching %0"});

merge(config.macros.tagging,{
	label: "tagging: ",
	labelNotTag: "not tagging",
	tooltip: "List of tiddlers tagged with '%0'"});

merge(config.macros.timeline,{
	dateFormat: "DD MMM YYYY"});

merge(config.macros.allTags,{
	tooltip: "Show tiddlers tagged with '%0'",
	noTags: "There are no tagged tiddlers"});

config.macros.list.all.prompt = "All tiddlers in alphabetical order";
config.macros.list.missing.prompt = "Tiddlers that have links to them but are not defined";
config.macros.list.orphans.prompt = "Tiddlers that are not linked to from any other tiddlers";
config.macros.list.shadowed.prompt = "Tiddlers shadowed with default contents";
config.macros.list.touched.prompt = "Tiddlers that have been modified locally";

merge(config.macros.closeAll,{
	label: "close all",
	prompt: "Close all displayed tiddlers (except any that are being edited)"});

merge(config.macros.permaview,{
	label: "permaview",
	prompt: "Link to an URL that retrieves all the currently displayed tiddlers"});

merge(config.macros.saveChanges,{
	label: "save changes",
	prompt: "Save all tiddlers to create a new TiddlyWiki",
	accessKey: "S"});

merge(config.macros.newTiddler,{
	label: "new tiddler",
	prompt: "Create a new tiddler",
	title: "New Tiddler",
	accessKey: "N"});

merge(config.macros.newJournal,{
	label: "new journal",
	prompt: "Create a new tiddler from the current date and time",
	accessKey: "J"});

merge(config.macros.options,{
	wizardTitle: "Tweak advanced options",
	step1Title: "These options are saved in cookies in your browser",
	step1Html: "<input type='hidden' name='markList'></input><br><input type='checkbox' checked='false' name='chkUnknown'>Show unknown options</input>",
	unknownDescription: "//(unknown)//",
	listViewTemplate: {
		columns: [
			{name: 'Option', field: 'option', title: "Option", type: 'String'},
			{name: 'Description', field: 'description', title: "Description", type: 'WikiText'},
			{name: 'Name', field: 'name', title: "Name", type: 'String'}
			],
		rowClasses: [
			{className: 'lowlight', field: 'lowlight'}
			]}
	});

merge(config.macros.plugins,{
	wizardTitle: "Manage plugins",
	step1Title: "Currently loaded plugins",
	step1Html: "<input type='hidden' name='markList'></input>", // DO NOT TRANSLATE
	skippedText: "(This plugin has not been executed because it was added since startup)",
	noPluginText: "There are no plugins installed",
	confirmDeleteText: "Are you sure you want to delete these plugins:\n\n%0",
	removeLabel: "remove systemConfig tag",
	removePrompt: "Remove systemConfig tag",
	deleteLabel: "delete",
	deletePrompt: "Delete these tiddlers forever",
	listViewTemplate: {
		columns: [
			{name: 'Selected', field: 'Selected', rowName: 'title', type: 'Selector'},
			{name: 'Tiddler', field: 'tiddler', title: "Tiddler", type: 'Tiddler'},
			{name: 'Description', field: 'Description', title: "Description", type: 'String'},
			{name: 'Version', field: 'Version', title: "Version", type: 'String'},
			{name: 'Size', field: 'size', tiddlerLink: 'size', title: "Size", type: 'Size'},
			{name: 'Forced', field: 'forced', title: "Forced", tag: 'systemConfigForce', type: 'TagCheckbox'},
			{name: 'Disabled', field: 'disabled', title: "Disabled", tag: 'systemConfigDisable', type: 'TagCheckbox'},
			{name: 'Executed', field: 'executed', title: "Loaded", type: 'Boolean', trueText: "Yes", falseText: "No"},
			{name: 'Startup Time', field: 'startupTime', title: "Startup Time", type: 'String'},
			{name: 'Error', field: 'error', title: "Status", type: 'Boolean', trueText: "Error", falseText: "OK"},
			{name: 'Log', field: 'log', title: "Log", type: 'StringList'}
			],
		rowClasses: [
			{className: 'error', field: 'error'},
			{className: 'warning', field: 'warning'}
			]},
	listViewTemplateReadOnly: {
		columns: [
			{name: 'Tiddler', field: 'tiddler', title: "Tiddler", type: 'Tiddler'},
			{name: 'Description', field: 'Description', title: "Description", type: 'String'},
			{name: 'Version', field: 'Version', title: "Version", type: 'String'},
			{name: 'Size', field: 'size', tiddlerLink: 'size', title: "Size", type: 'Size'},
			{name: 'Executed', field: 'executed', title: "Loaded", type: 'Boolean', trueText: "Yes", falseText: "No"},
			{name: 'Startup Time', field: 'startupTime', title: "Startup Time", type: 'String'},
			{name: 'Error', field: 'error', title: "Status", type: 'Boolean', trueText: "Error", falseText: "OK"},
			{name: 'Log', field: 'log', title: "Log", type: 'StringList'}
			],
		rowClasses: [
			{className: 'error', field: 'error'},
			{className: 'warning', field: 'warning'}
			]}
	});

merge(config.macros.toolbar,{
	moreLabel: "more",
	morePrompt: "Show additional commands",
	lessLabel: "less",
	lessPrompt: "Hide additional commands",
	separator: "|"
	});

merge(config.macros.refreshDisplay,{
	label: "refresh",
	prompt: "Redraw the entire TiddlyWiki display"
	});

merge(config.macros.importTiddlers,{
	readOnlyWarning: "You cannot import into a read-only TiddlyWiki file. Try opening it from a file:// URL",
	wizardTitle: "Import tiddlers from another file or server",
	step1Title: "Step 1: Locate the server or TiddlyWiki file",
	step1Html: "Specify the type of the server: <select name='selTypes'><option value=''>Choose...</option></select><br>Enter the URL or pathname here: <input type='text' size=50 name='txtPath'><br>...or browse for a file: <input type='file' size=50 name='txtBrowse'><br><hr>...or select a pre-defined feed: <select name='selFeeds'><option value=''>Choose...</option></select>",
	openLabel: "open",
	openPrompt: "Open the connection to this file or server",
	statusOpenHost: "Opening the host",
	statusGetWorkspaceList: "Getting the list of available workspaces",
	step2Title: "Step 2: Choose the workspace",
	step2Html: "Enter a workspace name: <input type='text' size=50 name='txtWorkspace'><br>...or select a workspace: <select name='selWorkspace'><option value=''>Choose...</option></select>",
	cancelLabel: "cancel",
	cancelPrompt: "Cancel this import",
	statusOpenWorkspace: "Opening the workspace",
	statusGetTiddlerList: "Getting the list of available tiddlers",
	errorGettingTiddlerList: "Error getting list of tiddlers, click Cancel to try again",
	step3Title: "Step 3: Choose the tiddlers to import",
	step3Html: "<input type='hidden' name='markList'></input><br><input type='checkbox' checked='true' name='chkSync'>Keep these tiddlers linked to this server so that you can synchronise subsequent changes</input><br><input type='checkbox' name='chkSave'>Save the details of this server in a 'systemServer' tiddler called:</input> <input type='text' size=25 name='txtSaveTiddler'>",
	importLabel: "import",
	importPrompt: "Import these tiddlers",
	confirmOverwriteText: "Are you sure you want to overwrite these tiddlers:\n\n%0",
	step4Title: "Step 4: Importing %0 tiddler(s)",
	step4Html: "<input type='hidden' name='markReport'></input>", // DO NOT TRANSLATE
	doneLabel: "done",
	donePrompt: "Close this wizard",
	statusDoingImport: "Importing tiddlers",
	statusDoneImport: "All tiddlers imported",
	systemServerNamePattern: "%2 on %1",
	systemServerNamePatternNoWorkspace: "%1",
	confirmOverwriteSaveTiddler: "The tiddler '%0' already exists. Click 'OK' to overwrite it with the details of this server, or 'Cancel' to leave it unchanged",
	serverSaveTemplate: "|''Type:''|%0|\n|''URL:''|%1|\n|''Workspace:''|%2|\n\nThis tiddler was automatically created to record the details of this server",
	serverSaveModifier: "(System)",
	listViewTemplate: {
		columns: [
			{name: 'Selected', field: 'Selected', rowName: 'title', type: 'Selector'},
			{name: 'Tiddler', field: 'tiddler', title: "Tiddler", type: 'Tiddler'},
			{name: 'Size', field: 'size', tiddlerLink: 'size', title: "Size", type: 'Size'},
			{name: 'Tags', field: 'tags', title: "Tags", type: 'Tags'}
			],
		rowClasses: [
			]}
	});

merge(config.macros.upgrade,{
	wizardTitle: "Upgrade TiddlyWiki core code",
	step1Title: "Update or repair this TiddlyWiki to the latest release",
	step1Html: "You are about to upgrade to the latest release of the TiddlyWiki core code (from <a href='%0' class='externalLink' target='_blank'>%1</a>). Your content will be preserved across the upgrade.<br><br>Note that core upgrades have been known to interfere with older plugins. If you run into problems with the upgraded file, see <a href='http://www.tiddlywiki.org/wiki/CoreUpgrades' class='externalLink' target='_blank'>http://www.tiddlywiki.org/wiki/CoreUpgrades</a>",
	errorCantUpgrade: "Unable to upgrade this TiddlyWiki. You can only perform upgrades on TiddlyWiki files stored locally",
	errorNotSaved: "You must save changes before you can perform an upgrade",
	step2Title: "Confirm the upgrade details",
	step2Html_downgrade: "You are about to downgrade to TiddlyWiki version %0 from %1.<br><br>Downgrading to an earlier version of the core code is not recommended",
	step2Html_restore: "This TiddlyWiki appears to be already using the latest version of the core code (%0).<br><br>You can continue to upgrade anyway to ensure that the core code hasn't been corrupted or damaged",
	step2Html_upgrade: "You are about to upgrade to TiddlyWiki version %0 from %1",
	upgradeLabel: "upgrade",
	upgradePrompt: "Prepare for the upgrade process",
	statusPreparingBackup: "Preparing backup",
	statusSavingBackup: "Saving backup file",
	errorSavingBackup: "There was a problem saving the backup file",
	statusLoadingCore: "Loading core code",
	errorLoadingCore: "Error loading the core code",
	errorCoreFormat: "Error with the new core code",
	statusSavingCore: "Saving the new core code",
	statusReloadingCore: "Reloading the new core code",
	startLabel: "start",
	startPrompt: "Start the upgrade process",
	cancelLabel: "cancel",
	cancelPrompt: "Cancel the upgrade process",
	step3Title: "Upgrade cancelled",
	step3Html: "You have cancelled the upgrade process"
	});

merge(config.macros.sync,{
	listViewTemplate: {
		columns: [
			{name: 'Selected', field: 'selected', rowName: 'title', type: 'Selector'},
			{name: 'Tiddler', field: 'tiddler', title: "Tiddler", type: 'Tiddler'},
			{name: 'Server Type', field: 'serverType', title: "Server type", type: 'String'},
			{name: 'Server Host', field: 'serverHost', title: "Server host", type: 'String'},
			{name: 'Server Workspace', field: 'serverWorkspace', title: "Server workspace", type: 'String'},
			{name: 'Status', field: 'status', title: "Synchronisation status", type: 'String'},
			{name: 'Server URL', field: 'serverUrl', title: "Server URL", text: "View", type: 'Link'}
			],
		rowClasses: [
			],
		buttons: [
			{caption: "Sync these tiddlers", name: 'sync'}
			]},
	wizardTitle: "Synchronize with external servers and files",
	step1Title: "Choose the tiddlers you want to synchronize",
	step1Html: "<input type='hidden' name='markList'></input>", // DO NOT TRANSLATE
	syncLabel: "sync",
	syncPrompt: "Sync these tiddlers",
	hasChanged: "Changed while unplugged",
	hasNotChanged: "Unchanged while unplugged",
	syncStatusList: {
		none: {text: "...", display:'none', className:'notChanged'},
		changedServer: {text: "Changed on server", display:null, className:'changedServer'},
		changedLocally: {text: "Changed while unplugged", display:null, className:'changedLocally'},
		changedBoth: {text: "Changed while unplugged and on server", display:null, className:'changedBoth'},
		notFound: {text: "Not found on server", display:null, className:'notFound'},
		putToServer: {text: "Saved update on server", display:null, className:'putToServer'},
		gotFromServer: {text: "Retrieved update from server", display:null, className:'gotFromServer'}
		}
	});

merge(config.macros.annotations,{
	});

merge(config.commands.closeTiddler,{
	text: "close",
	tooltip: "Close this tiddler"});

merge(config.commands.closeOthers,{
	text: "close others",
	tooltip: "Close all other tiddlers"});

merge(config.commands.editTiddler,{
	text: "edit",
	tooltip: "Edit this tiddler",
	readOnlyText: "view",
	readOnlyTooltip: "View the source of this tiddler"});

merge(config.commands.saveTiddler,{
	text: "done",
	tooltip: "Save changes to this tiddler"});

merge(config.commands.cancelTiddler,{
	text: "cancel",
	tooltip: "Undo changes to this tiddler",
	warning: "Are you sure you want to abandon your changes to '%0'?",
	readOnlyText: "done",
	readOnlyTooltip: "View this tiddler normally"});

merge(config.commands.deleteTiddler,{
	text: "delete",
	tooltip: "Delete this tiddler",
	warning: "Are you sure you want to delete '%0'?"});

merge(config.commands.permalink,{
	text: "permalink",
	tooltip: "Permalink for this tiddler"});

merge(config.commands.references,{
	text: "references",
	tooltip: "Show tiddlers that link to this one",
	popupNone: "No references"});

merge(config.commands.jump,{
	text: "jump",
	tooltip: "Jump to another open tiddler"});

merge(config.commands.syncing,{
	text: "syncing",
	tooltip: "Control synchronisation of this tiddler with a server or external file",
	currentlySyncing: "<div>Currently syncing via <span class='popupHighlight'>'%0'</span> to:</"+"div><div>host: <span class='popupHighlight'>%1</span></"+"div><div>workspace: <span class='popupHighlight'>%2</span></"+"div>", // Note escaping of closing <div> tag
	notCurrentlySyncing: "Not currently syncing",
	captionUnSync: "Stop synchronising this tiddler",
	chooseServer: "Synchronise this tiddler with another server:",
	currServerMarker: "\u25cf ",
	notCurrServerMarker: "  "});

merge(config.commands.fields,{
	text: "fields",
	tooltip: "Show the extended fields of this tiddler",
	emptyText: "There are no extended fields for this tiddler",
	listViewTemplate: {
		columns: [
			{name: 'Field', field: 'field', title: "Field", type: 'String'},
			{name: 'Value', field: 'value', title: "Value", type: 'String'}
			],
		rowClasses: [
			],
		buttons: [
			]}});

merge(config.shadowTiddlers,{
	DefaultTiddlers: "[[GettingStarted]]",
	MainMenu: "[[GettingStarted]]",
	SiteTitle: "My TiddlyWiki",
	SiteSubtitle: "a reusable non-linear personal web notebook",
	SiteUrl: "",
	SideBarOptions: '<<search>><<closeAll>><<permaview>><<newTiddler>><<newJournal "DD MMM YYYY" "journal">><<saveChanges>><<slider chkSliderOptionsPanel OptionsPanel "options \u00bb" "Change TiddlyWiki advanced options">>',
	SideBarTabs: '<<tabs txtMainTab "Timeline" "Timeline" TabTimeline "All" "All tiddlers" TabAll "Tags" "All tags" TabTags "More" "More lists" TabMore>>',
	TabMore: '<<tabs txtMoreTab "Missing" "Missing tiddlers" TabMoreMissing "Orphans" "Orphaned tiddlers" TabMoreOrphans "Shadowed" "Shadowed tiddlers" TabMoreShadowed>>'
	});

merge(config.annotations,{
	AdvancedOptions: "This shadow tiddler provides access to several advanced options",
	ColorPalette: "These values in this shadow tiddler determine the colour scheme of the ~TiddlyWiki user interface",
	DefaultTiddlers: "The tiddlers listed in this shadow tiddler will be automatically displayed when ~TiddlyWiki starts up",
	EditTemplate: "The HTML template in this shadow tiddler determines how tiddlers look while they are being edited",
	GettingStarted: "This shadow tiddler provides basic usage instructions",
	ImportTiddlers: "This shadow tiddler provides access to importing tiddlers",
	MainMenu: "This shadow tiddler is used as the contents of the main menu in the left-hand column of the screen",
	MarkupPreHead: "This tiddler is inserted at the top of the <head> section of the TiddlyWiki HTML file",
	MarkupPostHead: "This tiddler is inserted at the bottom of the <head> section of the TiddlyWiki HTML file",
	MarkupPreBody: "This tiddler is inserted at the top of the <body> section of the TiddlyWiki HTML file",
	MarkupPostBody: "This tiddler is inserted at the end of the <body> section of the TiddlyWiki HTML file immediately after the script block",
	OptionsPanel: "This shadow tiddler is used as the contents of the options panel slider in the right-hand sidebar",
	PageTemplate: "The HTML template in this shadow tiddler determines the overall ~TiddlyWiki layout",
	PluginManager: "This shadow tiddler provides access to the plugin manager",
	SideBarOptions: "This shadow tiddler is used as the contents of the option panel in the right-hand sidebar",
	SideBarTabs: "This shadow tiddler is used as the contents of the tabs panel in the right-hand sidebar",
	SiteSubtitle: "This shadow tiddler is used as the second part of the page title",
	SiteTitle: "This shadow tiddler is used as the first part of the page title",
	SiteUrl: "This shadow tiddler should be set to the full target URL for publication",
	StyleSheetColors: "This shadow tiddler contains CSS definitions related to the color of page elements. ''DO NOT EDIT THIS TIDDLER'', instead make your changes in the StyleSheet shadow tiddler",
	StyleSheet: "This tiddler can contain custom CSS definitions",
	StyleSheetLayout: "This shadow tiddler contains CSS definitions related to the layout of page elements. ''DO NOT EDIT THIS TIDDLER'', instead make your changes in the StyleSheet shadow tiddler",
	StyleSheetLocale: "This shadow tiddler contains CSS definitions related to the translation locale",
	StyleSheetPrint: "This shadow tiddler contains CSS definitions for printing",
	SystemSettings: "This tiddler is used to store configuration options for this TiddlyWiki document",
	TabAll: "This shadow tiddler contains the contents of the 'All' tab in the right-hand sidebar",
	TabMore: "This shadow tiddler contains the contents of the 'More' tab in the right-hand sidebar",
	TabMoreMissing: "This shadow tiddler contains the contents of the 'Missing' tab in the right-hand sidebar",
	TabMoreOrphans: "This shadow tiddler contains the contents of the 'Orphans' tab in the right-hand sidebar",
	TabMoreShadowed: "This shadow tiddler contains the contents of the 'Shadowed' tab in the right-hand sidebar",
	TabTags: "This shadow tiddler contains the contents of the 'Tags' tab in the right-hand sidebar",
	TabTimeline: "This shadow tiddler contains the contents of the 'Timeline' tab in the right-hand sidebar",
	ToolbarCommands: "This shadow tiddler determines which commands are shown in tiddler toolbars",
	ViewTemplate: "The HTML template in this shadow tiddler determines how tiddlers look"
	});
//--
//-- Main
//--

var params = null; // Command line parameters
var store = null; // TiddlyWiki storage
var story = null; // Main story
var formatter = null; // Default formatters for the wikifier
var anim = typeof Animator == "function" ? new Animator() : null; // Animation engine
var readOnly = false; // Whether we're in readonly mode
var highlightHack = null; // Embarrassing hack department...
var hadConfirmExit = false; // Don't warn more than once
var safeMode = false; // Disable all plugins and cookies
var showBackstage; // Whether to include the backstage area
var installedPlugins = []; // Information filled in when plugins are executed
var startingUp = false; // Whether we're in the process of starting up
var pluginInfo,tiddler; // Used to pass information to plugins in loadPlugins()

// Whether to use the JavaSaver applet
var useJavaSaver = (config.browser.isSafari || config.browser.isOpera) && (document.location.toString().substr(0,4) != "http");

// Starting up
function main()
{
	var t10,t9,t8,t7,t6,t5,t4,t3,t2,t1,t0 = new Date();
	startingUp = true;
	var doc = jQuery(document);
	jQuery.noConflict();
	window.onbeforeunload = function(e) {if(window.confirmExit) return confirmExit();};
	params = getParameters();
	if(params)
		params = params.parseParams("open",null,false);
	store = new TiddlyWiki();
	invokeParamifier(params,"oninit");
	story = new Story("tiddlerDisplay","tiddler");
	addEvent(document,"click",Popup.onDocumentClick);
	saveTest();
	for(var s=0; s<config.notifyTiddlers.length; s++)
		store.addNotification(config.notifyTiddlers[s].name,config.notifyTiddlers[s].notify);
	t1 = new Date();
	loadShadowTiddlers();
	doc.trigger("loadShadows");
	t2 = new Date();
	store.loadFromDiv("storeArea","store",true);
	doc.trigger("loadTiddlers");
	loadOptions();
	t3 = new Date();
	invokeParamifier(params,"onload");
	t4 = new Date();
	readOnly = (window.location.protocol == "file:") ? false : config.options.chkHttpReadOnly;
	var pluginProblem = loadPlugins("systemConfig");
	doc.trigger("loadPlugins");
	t5 = new Date();
	formatter = new Formatter(config.formatters);
	invokeParamifier(params,"onconfig");
	story.switchTheme(config.options.txtTheme);
	showBackstage = showBackstage !== undefined ? showBackstage : !readOnly;
	t6 = new Date();
	for(var m in config.macros) {
		if(config.macros[m].init)
			config.macros[m].init();
	}
	t7 = new Date();
	store.notifyAll();
	t8 = new Date();
	restart();
	refreshDisplay();
	t9 = new Date();
	if(pluginProblem) {
		story.displayTiddler(null,"PluginManager");
		displayMessage(config.messages.customConfigError);
	}
	if(showBackstage)
		backstage.init();
	t10 = new Date();
	if(config.options.chkDisplayInstrumentation) {
		displayMessage("LoadShadows " + (t2-t1) + " ms");
		displayMessage("LoadFromDiv " + (t3-t2) + " ms");
		displayMessage("LoadPlugins " + (t5-t4) + " ms");
		displayMessage("Macro init " + (t7-t6) + " ms");
		displayMessage("Notify " + (t8-t7) + " ms");
		displayMessage("Restart " + (t9-t8) + " ms");
		displayMessage("Total: " + (t10-t0) + " ms");
	}
	startingUp = false;
	doc.trigger("startup");
}

// Called on unload. All functions called conditionally since they themselves may have been unloaded.
function unload()
{
	if(window.checkUnsavedChanges)
		checkUnsavedChanges();
	if(window.scrubNodes)
		scrubNodes(document.body);
}

// Restarting
function restart()
{
	invokeParamifier(params,"onstart");
	if(story.isEmpty()) {
		story.displayDefaultTiddlers();
	}
	window.scrollTo(0,0);
}

function saveTest()
{
	var s = document.getElementById("saveTest");
	if(s.hasChildNodes())
		alert(config.messages.savedSnapshotError);
	s.appendChild(document.createTextNode("savetest"));
}

function loadShadowTiddlers()
{
	var shadows = new TiddlyWiki();
	shadows.loadFromDiv("shadowArea","shadows",true);
	shadows.forEachTiddler(function(title,tiddler){config.shadowTiddlers[title] = tiddler.text;});
}

function loadPlugins(tag)
{
	if(safeMode)
		return false;
	var tiddlers = store.getTaggedTiddlers(tag);
	tiddlers.sort(function(a,b) {return a.title < b.title ? -1 : (a.title == b.title ? 0 : 1);});
	var toLoad = [];
	var nLoaded = 0;
	var map = {};
	var nPlugins = tiddlers.length;
	installedPlugins = [];
	for(var i=0; i<nPlugins; i++) {
		var p = getPluginInfo(tiddlers[i]);
		installedPlugins[i] = p;
		var n = p.Name || p.title;
		if(n)
			map[n] = p;
		n = p.Source;
		if(n)
			map[n] = p;
	}
	var visit = function(p) {
		if(!p || p.done)
			return;
		p.done = 1;
		var reqs = p.Requires;
		if(reqs) {
			reqs = reqs.readBracketedList();
			for(var i=0; i<reqs.length; i++)
				visit(map[reqs[i]]);
		}
		toLoad.push(p);
	};
	for(i=0; i<nPlugins; i++)
		visit(installedPlugins[i]);
	for(i=0; i<toLoad.length; i++) {
		p = toLoad[i];
		pluginInfo = p;
		tiddler = p.tiddler;
		if(isPluginExecutable(p)) {
			if(isPluginEnabled(p)) {
				p.executed = true;
				var startTime = new Date();
				try {
					if(tiddler.text)
						window.eval(tiddler.text);
					nLoaded++;
				} catch(ex) {
					p.log.push(config.messages.pluginError.format([exceptionText(ex)]));
					p.error = true;
					if(!console.tiddlywiki) {
						console.log("error evaluating " + tiddler.title, ex);
					}
				}
				pluginInfo.startupTime = String((new Date()) - startTime) + "ms";
			} else {
				nPlugins--;
			}
		} else {
			p.warning = true;
		}
	}
	return nLoaded != nPlugins;
}

function getPluginInfo(tiddler)
{
	var p = store.getTiddlerSlices(tiddler.title,["Name","Description","Version","Requires","CoreVersion","Date","Source","Author","License","Browsers"]);
	p.tiddler = tiddler;
	p.title = tiddler.title;
	p.log = [];
	return p;
}

// Check that a particular plugin is valid for execution
function isPluginExecutable(plugin)
{
	if(plugin.tiddler.isTagged("systemConfigForce")) {
		plugin.log.push(config.messages.pluginForced);
		return true;
	}
	if(plugin["CoreVersion"]) {
		var coreVersion = plugin["CoreVersion"].split(".");
		var w = parseInt(coreVersion[0],10) - version.major;
		if(w == 0 && coreVersion[1])
			w = parseInt(coreVersion[1],10) - version.minor;
		if(w == 0 && coreVersion[2])
			w = parseInt(coreVersion[2],10) - version.revision;
		if(w > 0) {
			plugin.log.push(config.messages.pluginVersionError);
			return false;
		}
	}
	return true;
}

function isPluginEnabled(plugin)
{
	if(plugin.tiddler.isTagged("systemConfigDisable")) {
		plugin.log.push(config.messages.pluginDisabled);
		return false;
	}
	return true;
}

function invokeMacro(place,macro,params,wikifier,tiddler)
{
	try {
		var m = config.macros[macro];
		if(m && m.handler) {
			var tiddlerElem = story.findContainingTiddler(place);
			window.tiddler = tiddlerElem ? store.getTiddler(tiddlerElem.getAttribute("tiddler")) : null;
			window.place = place;
			var allowEval = true;
			if(config.evaluateMacroParameters=="system") {
				if(!tiddler || tiddler.tags.indexOf("systemAllowEval") == -1) {
					allowEval = false;
				}
			}
			m.handler(place,macro,m.noPreParse?null:params.readMacroParams(!allowEval),wikifier,params,tiddler);
		} else {
			createTiddlyError(place,config.messages.macroError.format([macro]),config.messages.macroErrorDetails.format([macro,config.messages.missingMacro]));
		}
	} catch(ex) {
		createTiddlyError(place,config.messages.macroError.format([macro]),config.messages.macroErrorDetails.format([macro,ex.toString()]));
	}
}

//--
//-- Paramifiers
//--

function getParameters()
{
	var p = null;
	if(window.location.hash) {
		p = decodeURIComponent(window.location.hash.substr(1));
		if(config.browser.firefoxDate != null && config.browser.firefoxDate[1] < "20051111")
			p = convertUTF8ToUnicode(p);
	}
	return p;
}

function invokeParamifier(params,handler)
{
	if(!params || params.length == undefined || params.length <= 1)
		return;
	for(var i=1; i<params.length; i++) {
		var p = config.paramifiers[params[i].name];
		if(p && p[handler] instanceof Function)
			p[handler](params[i].value);
		else {
			var h = config.optionHandlers[params[i].name.substr(0,3)];
			if(h && h.set instanceof Function)
				h.set(params[i].name,params[i].value);
		}
	}
}

config.paramifiers = {};

config.paramifiers.start = {
	oninit: function(v) {
		safeMode = v.toLowerCase() == "safe";
	}
};

config.paramifiers.open = {
	onstart: function(v) {
		if(!readOnly || store.tiddlerExists(v) || store.isShadowTiddler(v))
			story.displayTiddler("bottom",v,null,false,null);
	}
};

config.paramifiers.story = {
	onstart: function(v) {
		var list = store.getTiddlerText(v,"").parseParams("open",null,false);
		invokeParamifier(list,"onstart");
	}
};

config.paramifiers.search = {
	onstart: function(v) {
		story.search(v,false,false);
	}
};

config.paramifiers.searchRegExp = {
	onstart: function(v) {
		story.prototype.search(v,false,true);
	}
};

config.paramifiers.tag = {
	onstart: function(v) {
		story.displayTiddlers(null,store.filterTiddlers("[tag["+v+"]]"),null,false,null);
	}
};

config.paramifiers.newTiddler = {
	onstart: function(v) {
		if(!readOnly) {
			story.displayTiddler(null,v,DEFAULT_EDIT_TEMPLATE);
			story.focusTiddler(v,"text");
		}
	}
};

config.paramifiers.newJournal = {
	onstart: function(v) {
		if(!readOnly) {
			var now = new Date();
			var title = now.formatString(v.trim());
			story.displayTiddler(null,title,DEFAULT_EDIT_TEMPLATE);
			story.focusTiddler(title,"text");
		}
	}
};

config.paramifiers.readOnly = {
	onconfig: function(v) {
		var p = v.toLowerCase();
		readOnly = p == "yes" ? true : (p == "no" ? false : readOnly);
	}
};

config.paramifiers.theme = {
	onconfig: function(v) {
		story.switchTheme(v);
	}
};

config.paramifiers.upgrade = {
	onstart: function(v) {
		upgradeFrom(v);
	}
};

config.paramifiers.recent= {
	onstart: function(v) {
		var titles=[];
		var tiddlers=store.getTiddlers("modified","excludeLists").reverse();
		for(var i=0; i<v && i<tiddlers.length; i++)
			titles.push(tiddlers[i].title);
		story.displayTiddlers(null,titles);
	}
};

config.paramifiers.filter = {
	onstart: function(v) {
		story.displayTiddlers(null,store.filterTiddlers(v),null,false);
	}
};

//--
//-- Formatter helpers
//--

function Formatter(formatters)
{
	this.formatters = [];
	var pattern = [];
	for(var n=0; n<formatters.length; n++) {
		pattern.push("(" + formatters[n].match + ")");
		this.formatters.push(formatters[n]);
	}
	this.formatterRegExp = new RegExp(pattern.join("|"),"mg");
}

config.formatterHelpers = {

	createElementAndWikify: function(w)
	{
		w.subWikifyTerm(createTiddlyElement(w.output,this.element),this.termRegExp);
	},

	inlineCssHelper: function(w)
	{
		var styles = [];
		config.textPrimitives.cssLookaheadRegExp.lastIndex = w.nextMatch;
		var lookaheadMatch = config.textPrimitives.cssLookaheadRegExp.exec(w.source);
		while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {
			var s,v;
			if(lookaheadMatch[1]) {
				s = lookaheadMatch[1].unDash();
				v = lookaheadMatch[2];
			} else {
				s = lookaheadMatch[3].unDash();
				v = lookaheadMatch[4];
			}
			if(s=="bgcolor")
				s = "backgroundColor";
			if(s=="float")
				s = "cssFloat";
			styles.push({style: s, value: v});
			w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
			config.textPrimitives.cssLookaheadRegExp.lastIndex = w.nextMatch;
			lookaheadMatch = config.textPrimitives.cssLookaheadRegExp.exec(w.source);
		}
		return styles;
	},

	applyCssHelper: function(e,styles)
	{
		for(var t=0; t< styles.length; t++) {
			try {
				e.style[styles[t].style] = styles[t].value;
			} catch (ex) {
			}
		}
	},

	enclosedTextHelper: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			var text = lookaheadMatch[1];
			if(config.browser.isIE)
				text = text.replace(/\n/g,"\r");
			createTiddlyElement(w.output,this.element,null,null,text);
			w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
		}
	},

	isExternalLink: function(link)
	{
		if(store.tiddlerExists(link) || store.isShadowTiddler(link)) {
			return false;
		}
		var urlRegExp = new RegExp(config.textPrimitives.urlPattern,"mg");
		if(urlRegExp.exec(link)) {
			return true;
		}
		if(link.indexOf(".")!=-1 || link.indexOf("\\")!=-1 || link.indexOf("/")!=-1 || link.indexOf("#")!=-1) {
			return true;
		}
		return false;
	}

};

//--
//-- Standard formatters
//--

config.formatters = [
{
	name: "table",
	match: "^\\|(?:[^\\n]*)\\|(?:[fhck]?)$",
	lookaheadRegExp: /^\|([^\n]*)\|([fhck]?)$/mg,
	rowTermRegExp: /(\|(?:[fhck]?)$\n?)/mg,
	cellRegExp: /(?:\|([^\n\|]*)\|)|(\|[fhck]?$\n?)/mg,
	cellTermRegExp: /((?:\x20*)\|)/mg,
	rowTypes: {"c":"caption", "h":"thead", "":"tbody", "f":"tfoot"},
	handler: function(w)
	{
		var table = createTiddlyElement(w.output,"table",null,"twtable");
		var prevColumns = [];
		var currRowType = null;
		var rowContainer;
		var rowCount = 0;
		w.nextMatch = w.matchStart;
		this.lookaheadRegExp.lastIndex = w.nextMatch;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {
			var nextRowType = lookaheadMatch[2];
			if(nextRowType == "k") {
				table.className = lookaheadMatch[1];
				w.nextMatch += lookaheadMatch[0].length+1;
			} else {
				if(nextRowType != currRowType) {
					rowContainer = createTiddlyElement(table,this.rowTypes[nextRowType]);
					currRowType = nextRowType;
				}
				if(currRowType == "c") {
					// Caption
					w.nextMatch++;
					if(rowContainer != table.firstChild)
						table.insertBefore(rowContainer,table.firstChild);
					rowContainer.setAttribute("align",rowCount == 0?"top":"bottom");
					w.subWikifyTerm(rowContainer,this.rowTermRegExp);
				} else {
					var theRow = createTiddlyElement(rowContainer,"tr",null,(rowCount&1)?"oddRow":"evenRow");
					theRow.onmouseover = function() {addClass(this,"hoverRow");};
					theRow.onmouseout = function() {removeClass(this,"hoverRow");};
					this.rowHandler(w,theRow,prevColumns);
					rowCount++;
				}
			}
			this.lookaheadRegExp.lastIndex = w.nextMatch;
			lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		}
	},
	rowHandler: function(w,e,prevColumns)
	{
		var col = 0;
		var colSpanCount = 1;
		var prevCell = null;
		this.cellRegExp.lastIndex = w.nextMatch;
		var cellMatch = this.cellRegExp.exec(w.source);
		while(cellMatch && cellMatch.index == w.nextMatch) {
			if(cellMatch[1] == "~") {
				// Rowspan
				var last = prevColumns[col];
				if(last) {
					last.rowSpanCount++;
					last.element.setAttribute("rowspan",last.rowSpanCount);
					last.element.setAttribute("rowSpan",last.rowSpanCount); // Needed for IE
					last.element.valign = "center";
					if(colSpanCount > 1) {
						last.element.setAttribute("colspan",colSpanCount);
						last.element.setAttribute("colSpan",colSpanCount); // Needed for IE
						colSpanCount = 1;
					}
				}
				w.nextMatch = this.cellRegExp.lastIndex-1;
			} else if(cellMatch[1] == ">") {
				// Colspan
				colSpanCount++;
				w.nextMatch = this.cellRegExp.lastIndex-1;
			} else if(cellMatch[2]) {
				// End of row
				if(prevCell && colSpanCount > 1) {
					prevCell.setAttribute("colspan",colSpanCount);
					prevCell.setAttribute("colSpan",colSpanCount); // Needed for IE
				}
				w.nextMatch = this.cellRegExp.lastIndex;
				break;
			} else {
				// Cell
				w.nextMatch++;
				var styles = config.formatterHelpers.inlineCssHelper(w);
				var spaceLeft = false;
				var chr = w.source.substr(w.nextMatch,1);
				while(chr == " ") {
					spaceLeft = true;
					w.nextMatch++;
					chr = w.source.substr(w.nextMatch,1);
				}
				var cell;
				if(chr == "!") {
					cell = createTiddlyElement(e,"th");
					w.nextMatch++;
				} else {
					cell = createTiddlyElement(e,"td");
				}
				prevCell = cell;
				prevColumns[col] = {rowSpanCount:1,element:cell};
				if(colSpanCount > 1) {
					cell.setAttribute("colspan",colSpanCount);
					cell.setAttribute("colSpan",colSpanCount); // Needed for IE
					colSpanCount = 1;
				}
				config.formatterHelpers.applyCssHelper(cell,styles);
				w.subWikifyTerm(cell,this.cellTermRegExp);
				if(w.matchText.substr(w.matchText.length-2,1) == " ") // spaceRight
					cell.align = spaceLeft ? "center" : "left";
				else if(spaceLeft)
					cell.align = "right";
				w.nextMatch--;
			}
			col++;
			this.cellRegExp.lastIndex = w.nextMatch;
			cellMatch = this.cellRegExp.exec(w.source);
		}
	}
},

{
	name: "heading",
	match: "^!{1,6}",
	termRegExp: /(\n)/mg,
	handler: function(w)
	{
		w.subWikifyTerm(createTiddlyElement(w.output,"h" + w.matchLength),this.termRegExp);
	}
},

{
	name: "list",
	match: "^(?:[\\*#;:]+)",
	lookaheadRegExp: /^(?:(?:(\*)|(#)|(;)|(:))+)/mg,
	termRegExp: /(\n)/mg,
	handler: function(w)
	{
		var stack = [w.output];
		var currLevel = 0, currType = null;
		var listLevel, listType, itemType, baseType;
		w.nextMatch = w.matchStart;
		this.lookaheadRegExp.lastIndex = w.nextMatch;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		while(lookaheadMatch && lookaheadMatch.index == w.nextMatch) {
			if(lookaheadMatch[1]) {
				listType = "ul";
				itemType = "li";
			} else if(lookaheadMatch[2]) {
				listType = "ol";
				itemType = "li";
			} else if(lookaheadMatch[3]) {
				listType = "dl";
				itemType = "dt";
			} else if(lookaheadMatch[4]) {
				listType = "dl";
				itemType = "dd";
			}
			if(!baseType)
				baseType = listType;
			listLevel = lookaheadMatch[0].length;
			w.nextMatch += lookaheadMatch[0].length;
			var t;
			if(listLevel > currLevel) {
				for(t=currLevel; t<listLevel; t++) {
					var target = (currLevel == 0) ? stack[stack.length-1] : stack[stack.length-1].lastChild;
					stack.push(createTiddlyElement(target,listType));
				}
			} else if(listType!=baseType && listLevel==1) {
				w.nextMatch -= lookaheadMatch[0].length;
				return;
			} else if(listLevel < currLevel) {
				for(t=currLevel; t>listLevel; t--)
					stack.pop();
			} else if(listLevel == currLevel && listType != currType) {
				stack.pop();
				stack.push(createTiddlyElement(stack[stack.length-1].lastChild,listType));
			}
			currLevel = listLevel;
			currType = listType;
			var e = createTiddlyElement(stack[stack.length-1],itemType);
			w.subWikifyTerm(e,this.termRegExp);
			this.lookaheadRegExp.lastIndex = w.nextMatch;
			lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		}
	}
},

{
	name: "quoteByBlock",
	match: "^<<<\\n",
	termRegExp: /(^<<<(\n|$))/mg,
	element: "blockquote",
	handler: config.formatterHelpers.createElementAndWikify
},

{
	name: "quoteByLine",
	match: "^>+",
	lookaheadRegExp: /^>+/mg,
	termRegExp: /(\n)/mg,
	element: "blockquote",
	handler: function(w)
	{
		var stack = [w.output];
		var currLevel = 0;
		var newLevel = w.matchLength;
		var t;
		do {
			if(newLevel > currLevel) {
				for(t=currLevel; t<newLevel; t++)
					stack.push(createTiddlyElement(stack[stack.length-1],this.element));
			} else if(newLevel < currLevel) {
				for(t=currLevel; t>newLevel; t--)
					stack.pop();
			}
			currLevel = newLevel;
			w.subWikifyTerm(stack[stack.length-1],this.termRegExp);
			createTiddlyElement(stack[stack.length-1],"br");
			this.lookaheadRegExp.lastIndex = w.nextMatch;
			var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
			var matched = lookaheadMatch && lookaheadMatch.index == w.nextMatch;
			if(matched) {
				newLevel = lookaheadMatch[0].length;
				w.nextMatch += lookaheadMatch[0].length;
			}
		} while(matched);
	}
},

{
	name: "rule",
	match: "^----+$\\n?|<hr ?/?>\\n?",
	handler: function(w)
	{
		createTiddlyElement(w.output,"hr");
	}
},

{
	name: "monospacedByLine",
	match: "^(?:/\\*\\{\\{\\{\\*/|\\{\\{\\{|//\\{\\{\\{|<!--\\{\\{\\{-->)\\n",
	element: "pre",
	handler: function(w)
	{
		switch(w.matchText) {
		case "/*{{{*/\n": // CSS
			this.lookaheadRegExp = /\/\*\{\{\{\*\/\n*((?:^[^\n]*\n)+?)(\n*^\f*\/\*\}\}\}\*\/$\n?)/mg;
			break;
		case "{{{\n": // monospaced block
			this.lookaheadRegExp = /^\{\{\{\n((?:^[^\n]*\n)+?)(^\f*\}\}\}$\n?)/mg;
			break;
		case "//{{{\n": // plugin
			this.lookaheadRegExp = /^\/\/\{\{\{\n\n*((?:^[^\n]*\n)+?)(\n*^\f*\/\/\}\}\}$\n?)/mg;
			break;
		case "<!--{{{-->\n": //template
			this.lookaheadRegExp = /<!--\{\{\{-->\n*((?:^[^\n]*\n)+?)(\n*^\f*<!--\}\}\}-->$\n?)/mg;
			break;
		default:
			break;
		}
		config.formatterHelpers.enclosedTextHelper.call(this,w);
	}
},

{
	name: "wikifyComment",
	match: "^(?:/\\*\\*\\*|<!---)\\n",
	handler: function(w)
	{
		var termRegExp = (w.matchText == "/***\n") ? (/(^\*\*\*\/\n)/mg) : (/(^--->\n)/mg);
		w.subWikifyTerm(w.output,termRegExp);
	}
},

{
	name: "macro",
	match: "<<",
	lookaheadRegExp: /<<([^>\s]+)(?:\s*)((?:[^>]|(?:>(?!>)))*)>>/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart && lookaheadMatch[1]) {
			w.nextMatch = this.lookaheadRegExp.lastIndex;
			invokeMacro(w.output,lookaheadMatch[1],lookaheadMatch[2],w,w.tiddler);
		}
	}
},

{
	name: "prettyLink",
	match: "\\[\\[",
	lookaheadRegExp: /\[\[(.*?)(?:\|(~)?(.*?))?\]\]/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			var e;
			var text = lookaheadMatch[1];
			if(lookaheadMatch[3]) {
				// Pretty bracketted link
				var link = lookaheadMatch[3];
				e = (!lookaheadMatch[2] && config.formatterHelpers.isExternalLink(link)) ?
						createExternalLink(w.output,link) : createTiddlyLink(w.output,link,false,null,w.isStatic,w.tiddler);
			} else {
				// Simple bracketted link
				e = createTiddlyLink(w.output,text,false,null,w.isStatic,w.tiddler);
			}
			createTiddlyText(e,text);
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
},

{
	name: "wikiLink",
	match: config.textPrimitives.unWikiLink+"?"+config.textPrimitives.wikiLink,
	handler: function(w)
	{
		if(w.matchText.substr(0,1) == config.textPrimitives.unWikiLink) {
			w.outputText(w.output,w.matchStart+1,w.nextMatch);
			return;
		}
		if(w.matchStart > 0) {
			var preRegExp = new RegExp(config.textPrimitives.anyLetterStrict,"mg");
			preRegExp.lastIndex = w.matchStart-1;
			var preMatch = preRegExp.exec(w.source);
			if(preMatch.index == w.matchStart-1) {
				w.outputText(w.output,w.matchStart,w.nextMatch);
				return;
			}
		}
		if(w.autoLinkWikiWords || store.isShadowTiddler(w.matchText)) {
			var link = createTiddlyLink(w.output,w.matchText,false,null,w.isStatic,w.tiddler);
			w.outputText(link,w.matchStart,w.nextMatch);
		} else {
			w.outputText(w.output,w.matchStart,w.nextMatch);
		}
	}
},

{
	name: "urlLink",
	match: config.textPrimitives.urlPattern,
	handler: function(w)
	{
		w.outputText(createExternalLink(w.output,w.matchText),w.matchStart,w.nextMatch);
	}
},

{
	name: "image",
	match: "\\[[<>]?[Ii][Mm][Gg]\\[",
	lookaheadRegExp: /\[([<]?)(>?)[Ii][Mm][Gg]\[(?:([^\|\]]+)\|)?([^\[\]\|]+)\](?:\[([^\]]*)\])?\]/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			var e = w.output;
			if(lookaheadMatch[5]) {
				var link = lookaheadMatch[5];
				e = config.formatterHelpers.isExternalLink(link) ? createExternalLink(w.output,link) : createTiddlyLink(w.output,link,false,null,w.isStatic,w.tiddler);
				addClass(e,"imageLink");
			}
			var img = createTiddlyElement(e,"img");
			if(lookaheadMatch[1])
				img.align = "left";
			else if(lookaheadMatch[2])
				img.align = "right";
			if(lookaheadMatch[3]) {
				img.title = lookaheadMatch[3];
				img.setAttribute("alt",lookaheadMatch[3]);
			}
			img.src = lookaheadMatch[4];
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
},

{
	name: "html",
	match: "<[Hh][Tt][Mm][Ll]>",
	lookaheadRegExp: /<[Hh][Tt][Mm][Ll]>((?:.|\n)*?)<\/[Hh][Tt][Mm][Ll]>/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			createTiddlyElement(w.output,"span").innerHTML = lookaheadMatch[1];
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
},

{
	name: "commentByBlock",
	match: "/%",
	lookaheadRegExp: /\/%((?:.|\n)*?)%\//mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart)
			w.nextMatch = this.lookaheadRegExp.lastIndex;
	}
},

{
	name: "characterFormat",
	match: "''|//|__|\\^\\^|~~|--(?!\\s|$)|\\{\\{\\{",
	handler: function(w)
	{
		switch(w.matchText) {
		case "''":
			w.subWikifyTerm(w.output.appendChild(document.createElement("strong")),/('')/mg);
			break;
		case "//":
			w.subWikifyTerm(createTiddlyElement(w.output,"em"),/(\/\/)/mg);
			break;
		case "__":
			w.subWikifyTerm(createTiddlyElement(w.output,"u"),/(__)/mg);
			break;
		case "^^":
			w.subWikifyTerm(createTiddlyElement(w.output,"sup"),/(\^\^)/mg);
			break;
		case "~~":
			w.subWikifyTerm(createTiddlyElement(w.output,"sub"),/(~~)/mg);
			break;
		case "--":
			w.subWikifyTerm(createTiddlyElement(w.output,"strike"),/(--)/mg);
			break;
		case "{{{":
			var lookaheadRegExp = /\{\{\{((?:.|\n)*?)\}\}\}/mg;
			lookaheadRegExp.lastIndex = w.matchStart;
			var lookaheadMatch = lookaheadRegExp.exec(w.source);
			if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
				createTiddlyElement(w.output,"code",null,null,lookaheadMatch[1]);
				w.nextMatch = lookaheadRegExp.lastIndex;
			}
			break;
		}
	}
},

{
	name: "customFormat",
	match: "@@|\\{\\{",
	handler: function(w)
	{
		switch(w.matchText) {
		case "@@":
			var e = createTiddlyElement(w.output,"span");
			var styles = config.formatterHelpers.inlineCssHelper(w);
			if(styles.length == 0)
				e.className = "marked";
			else
				config.formatterHelpers.applyCssHelper(e,styles);
			w.subWikifyTerm(e,/(@@)/mg);
			break;
		case "{{":
			var lookaheadRegExp = /\{\{[\s]*([\w]+[\s\w]*)[\s]*\{(\n?)/mg;
			lookaheadRegExp.lastIndex = w.matchStart;
			var lookaheadMatch = lookaheadRegExp.exec(w.source);
			if(lookaheadMatch) {
				w.nextMatch = lookaheadRegExp.lastIndex;
				e = createTiddlyElement(w.output,lookaheadMatch[2] == "\n" ? "div" : "span",null,lookaheadMatch[1]);
				w.subWikifyTerm(e,/(\}\}\})/mg);
			}
			break;
		}
	}
},

{
	name: "mdash",
	match: "--",
	handler: function(w)
	{
		createTiddlyElement(w.output,"span").innerHTML = "&mdash;";
	}
},

{
	name: "lineBreak",
	match: "\\n|<br ?/?>",
	handler: function(w)
	{
		createTiddlyElement(w.output,"br");
	}
},

{
	name: "rawText",
	match: "\"{3}|<nowiki>",
	lookaheadRegExp: /(?:\"{3}|<nowiki>)((?:.|\n)*?)(?:\"{3}|<\/nowiki>)/mg,
	handler: function(w)
	{
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			createTiddlyElement(w.output,"span",null,null,lookaheadMatch[1]);
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
},

{
	name: "htmlEntitiesEncoding",
	match: "(?:(?:&#?[a-zA-Z0-9]{2,8};|.)(?:&#?(?:x0*(?:3[0-6][0-9a-fA-F]|1D[c-fC-F][0-9a-fA-F]|20[d-fD-F][0-9a-fA-F]|FE2[0-9a-fA-F])|0*(?:76[89]|7[7-9][0-9]|8[0-7][0-9]|761[6-9]|76[2-7][0-9]|84[0-3][0-9]|844[0-7]|6505[6-9]|6506[0-9]|6507[0-1]));)+|&#?[a-zA-Z0-9]{2,8};)",
	handler: function(w)
	{
		createTiddlyElement(w.output,"span").innerHTML = w.matchText;
	}
}

];

//--
//-- Wikifier
//--

function getParser(tiddler,format)
{
	if(tiddler) {
		if(!format)
			format = tiddler.fields["wikiformat"];
		var i;
		if(format) {
			for(i in config.parsers) {
				if(format == config.parsers[i].format)
					return config.parsers[i];
			}
		} else {
			for(i in config.parsers) {
				if(tiddler.isTagged(config.parsers[i].formatTag))
					return config.parsers[i];
			}
		}
	}
	return formatter;
}

function wikify(source,output,highlightRegExp,tiddler)
{
	if(source) {
		var wikifier = new Wikifier(source,getParser(tiddler),highlightRegExp,tiddler);
		var t0 = new Date();
		wikifier.subWikify(output);
		if(tiddler && config.options.chkDisplayInstrumentation)
			displayMessage("wikify:" +tiddler.title+ " in " + (new Date()-t0) + " ms");
	}
}

function wikifyStatic(source,highlightRegExp,tiddler,format)
{
	var e = createTiddlyElement(document.body,"pre");
	e.style.display = "none";
	var html = "";
	if(source && source != "") {
		if(!tiddler)
			tiddler = new Tiddler("temp");
		var wikifier = new Wikifier(source,getParser(tiddler,format),highlightRegExp,tiddler);
		wikifier.isStatic = true;
		wikifier.subWikify(e);
		html = e.innerHTML;
		removeNode(e);
	}
	return html;
}

function wikifyPlain(title,theStore,limit)
{
	if(!theStore)
		theStore = store;
	if(theStore.tiddlerExists(title) || theStore.isShadowTiddler(title)) {
		return wikifyPlainText(theStore.getTiddlerText(title),limit,tiddler);
	} else {
		return "";
	}
}

function wikifyPlainText(text,limit,tiddler)
{
	if(limit > 0)
		text = text.substr(0,limit);
	var wikifier = new Wikifier(text,formatter,null,tiddler);
	return wikifier.wikifyPlain();
}

function highlightify(source,output,highlightRegExp,tiddler)
{
	if(source) {
		var wikifier = new Wikifier(source,formatter,highlightRegExp,tiddler);
		wikifier.outputText(output,0,source.length);
	}
}

function Wikifier(source,formatter,highlightRegExp,tiddler)
{
	this.source = source;
	this.output = null;
	this.formatter = formatter;
	this.nextMatch = 0;
	this.autoLinkWikiWords = tiddler && tiddler.autoLinkWikiWords() == false ? false : true;
	this.highlightRegExp = highlightRegExp;
	this.highlightMatch = null;
	this.isStatic = false;
	if(highlightRegExp) {
		highlightRegExp.lastIndex = 0;
		this.highlightMatch = highlightRegExp.exec(source);
	}
	this.tiddler = tiddler;
}

Wikifier.prototype.wikifyPlain = function()
{
	var e = createTiddlyElement(document.body,"div");
	e.style.display = "none";
	this.subWikify(e);
	var text = getPlainText(e);
	removeNode(e);
	return text;
};

Wikifier.prototype.subWikify = function(output,terminator)
{
	try {
		if(terminator)
			this.subWikifyTerm(output,new RegExp("(" + terminator + ")","mg"));
		else
			this.subWikifyUnterm(output);
	} catch(ex) {
		showException(ex);
	}
};

Wikifier.prototype.subWikifyUnterm = function(output)
{
	var oldOutput = this.output;
	this.output = output;
	this.formatter.formatterRegExp.lastIndex = this.nextMatch;
	var formatterMatch = this.formatter.formatterRegExp.exec(this.source);
	while(formatterMatch) {
		// Output any text before the match
		if(formatterMatch.index > this.nextMatch)
			this.outputText(this.output,this.nextMatch,formatterMatch.index);
		// Set the match parameters for the handler
		this.matchStart = formatterMatch.index;
		this.matchLength = formatterMatch[0].length;
		this.matchText = formatterMatch[0];
		this.nextMatch = this.formatter.formatterRegExp.lastIndex;
		for(var t=1; t<formatterMatch.length; t++) {
			if(formatterMatch[t]) {
				this.formatter.formatters[t-1].handler(this);
				this.formatter.formatterRegExp.lastIndex = this.nextMatch;
				break;
			}
		}
		formatterMatch = this.formatter.formatterRegExp.exec(this.source);
	}
	if(this.nextMatch < this.source.length) {
		this.outputText(this.output,this.nextMatch,this.source.length);
		this.nextMatch = this.source.length;
	}
	this.output = oldOutput;
};

Wikifier.prototype.subWikifyTerm = function(output,terminatorRegExp)
{
	var oldOutput = this.output;
	this.output = output;
	terminatorRegExp.lastIndex = this.nextMatch;
	var terminatorMatch = terminatorRegExp.exec(this.source);
	this.formatter.formatterRegExp.lastIndex = this.nextMatch;
	var formatterMatch = this.formatter.formatterRegExp.exec(terminatorMatch ? this.source.substr(0,terminatorMatch.index) : this.source);
	while(terminatorMatch || formatterMatch) {
		if(terminatorMatch && (!formatterMatch || terminatorMatch.index <= formatterMatch.index)) {
			if(terminatorMatch.index > this.nextMatch)
				this.outputText(this.output,this.nextMatch,terminatorMatch.index);
			this.matchText = terminatorMatch[1];
			this.matchLength = terminatorMatch[1].length;
			this.matchStart = terminatorMatch.index;
			this.nextMatch = this.matchStart + this.matchLength;
			this.output = oldOutput;
			return;
		}
		if(formatterMatch.index > this.nextMatch)
			this.outputText(this.output,this.nextMatch,formatterMatch.index);
		this.matchStart = formatterMatch.index;
		this.matchLength = formatterMatch[0].length;
		this.matchText = formatterMatch[0];
		this.nextMatch = this.formatter.formatterRegExp.lastIndex;
		for(var t=1; t<formatterMatch.length; t++) {
			if(formatterMatch[t]) {
				this.formatter.formatters[t-1].handler(this);
				this.formatter.formatterRegExp.lastIndex = this.nextMatch;
				break;
			}
		}
		terminatorRegExp.lastIndex = this.nextMatch;
		terminatorMatch = terminatorRegExp.exec(this.source);
		formatterMatch = this.formatter.formatterRegExp.exec(terminatorMatch ? this.source.substr(0,terminatorMatch.index) : this.source);
	}
	if(this.nextMatch < this.source.length) {
		this.outputText(this.output,this.nextMatch,this.source.length);
		this.nextMatch = this.source.length;
	}
	this.output = oldOutput;
};

Wikifier.prototype.outputText = function(place,startPos,endPos)
{
	while(this.highlightMatch && (this.highlightRegExp.lastIndex > startPos) && (this.highlightMatch.index < endPos) && (startPos < endPos)) {
		if(this.highlightMatch.index > startPos) {
			createTiddlyText(place,this.source.substring(startPos,this.highlightMatch.index));
			startPos = this.highlightMatch.index;
		}
		var highlightEnd = Math.min(this.highlightRegExp.lastIndex,endPos);
		var theHighlight = createTiddlyElement(place,"span",null,"highlight",this.source.substring(startPos,highlightEnd));
		startPos = highlightEnd;
		if(startPos >= this.highlightRegExp.lastIndex)
			this.highlightMatch = this.highlightRegExp.exec(this.source);
	}
	if(startPos < endPos) {
		createTiddlyText(place,this.source.substring(startPos,endPos));
	}
};

//--
//-- Macro definitions
//--

config.macros.today.handler = function(place,macroName,params)
{
	var now = new Date();
	var text = params[0] ? now.formatString(params[0].trim()) : now.toLocaleString();
	jQuery("<span/>").text(text).appendTo(place);
};

config.macros.version.handler = function(place)
{
	jQuery("<span/>").text(formatVersion()).appendTo(place);
};

config.macros.list.handler = function(place,macroName,params)
{
	var type = params[0] || "all";
	var list = document.createElement("ul");
	place.appendChild(list);
	if(this[type].prompt)
		createTiddlyElement(list,"li",null,"listTitle",this[type].prompt);
	var results;
	if(this[type].handler)
		results = this[type].handler(params);
	for(var t = 0; t < results.length; t++) {
		var li = document.createElement("li");
		list.appendChild(li);
		createTiddlyLink(li,typeof results[t] == "string" ? results[t] : results[t].title,true);
	}
};

config.macros.list.all.handler = function(params)
{
	return store.reverseLookup("tags","excludeLists",false,"title");
};

config.macros.list.missing.handler = function(params)
{
	return store.getMissingLinks();
};

config.macros.list.orphans.handler = function(params)
{
	return store.getOrphans();
};

config.macros.list.shadowed.handler = function(params)
{
	return store.getShadowed();
};

config.macros.list.touched.handler = function(params)
{
	return store.getTouched();
};

config.macros.list.filter.handler = function(params)
{
	var filter = params[1];
	var results = [];
	if(filter) {
		var tiddlers = store.filterTiddlers(filter);
		for(var t=0; t<tiddlers.length; t++)
			results.push(tiddlers[t].title);
	}
	return results;
};

config.macros.allTags.handler = function(place,macroName,params)
{
	var tags = store.getTags(params[0]);
	var ul = createTiddlyElement(place,"ul");
	if(tags.length == 0)
		createTiddlyElement(ul,"li",null,"listTitle",this.noTags);
	for(var t=0; t<tags.length; t++) {
		var title = tags[t][0];
		var info = getTiddlyLinkInfo(title);
		var li = createTiddlyElement(ul,"li");
		var btn = createTiddlyButton(li,title + " (" + tags[t][1] + ")",this.tooltip.format([title]),onClickTag,info.classes);
		btn.setAttribute("tag",title);
		btn.setAttribute("refresh","link");
		btn.setAttribute("tiddlyLink",title);
		if(params[1]) {
			btn.setAttribute("sortby",params[1]);
		}
	}
};

config.macros.timeline.handler = function(place,macroName,params)
{
	var field = params[0] || "modified";
	var tiddlers = store.reverseLookup("tags","excludeLists",false,field);
	var lastDay = "";
	var last = params[1] ? tiddlers.length-Math.min(tiddlers.length,parseInt(params[1])) : 0;
	var dateFormat = params[2] || this.dateFormat;
	for(var t=tiddlers.length-1; t>=last; t--) {
		var tiddler = tiddlers[t];
		var theDay = tiddler[field].convertToLocalYYYYMMDDHHMM().substr(0,8);
		if(theDay != lastDay) {
			var ul = document.createElement("ul");
			addClass(ul,"timeline");
			place.appendChild(ul);
			createTiddlyElement(ul,"li",null,"listTitle",tiddler[field].formatString(dateFormat));
			lastDay = theDay;
		}
		createTiddlyElement(ul,"li",null,"listLink").appendChild(createTiddlyLink(place,tiddler.title,true));
	}
};

config.macros.tiddler.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var allowEval = true;
	var stack = config.macros.tiddler.tiddlerStack;
	if(stack.length > 0 && config.evaluateMacroParameters == "system") {
		// included tiddler and "system" evaluation required, so check tiddler tagged appropriately
		var title = stack[stack.length-1];
		var pos = title.indexOf(config.textPrimitives.sectionSeparator);
		if(pos != -1) {
			title = title.substr(0,pos); // get the base tiddler title
		}
		var t = store.getTiddler(title);
		if(!t || t.tags.indexOf("systemAllowEval") == -1) {
			allowEval = false;
		}
	}
	params = paramString.parseParams("name",null,allowEval,false,true);
	var names = params[0]["name"];
	var tiddlerName = names[0];
	var className = names[1] || null;
	var args = params[0]["with"];
	var wrapper = createTiddlyElement(place,"span",null,className,null,{
		refresh: "content", tiddler: tiddlerName
	});
	if(args!==undefined)
		wrapper.setAttribute("args","[["+args.join("]] [[")+"]]");
	this.transclude(wrapper,tiddlerName,args);
};

config.macros.tiddler.transclude = function(wrapper,tiddlerName,args)
{
	var text = store.getTiddlerText(tiddlerName);
	if(!text)
		return;
	var stack = config.macros.tiddler.tiddlerStack;
	if(stack.indexOf(tiddlerName) !== -1)
		return;
	stack.push(tiddlerName);
	try {
		if(typeof args == "string")
			args = args.readBracketedList();
		var n = args ? Math.min(args.length,9) : 0;
		for(var i=0; i<n; i++) {
			var placeholderRE = new RegExp("\\$" + (i + 1),"mg");
			text = text.replace(placeholderRE,args[i]);
		}
		config.macros.tiddler.renderText(wrapper,text,tiddlerName,params);
	} finally {
		stack.pop();
	}
};

config.macros.tiddler.renderText = function(place,text,tiddlerName,params)
{
	wikify(text,place,null,store.getTiddler(tiddlerName));
};

config.macros.tiddler.tiddlerStack = [];

config.macros.tag.handler = function(place,macroName,params)
{
	createTagButton(place,params[0],null,params[1],params[2]);
	if(params[3]) {
		btn.setAttribute('sortby',params[3]);
	}
};

config.macros.tags.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	params = paramString.parseParams("anon",null,true,false,false);
	var ul = createTiddlyElement(place,"ul");
	var title = getParam(params,"anon","");
	if(title && store.tiddlerExists(title))
		tiddler = store.getTiddler(title);
	var sep = getParam(params,"sep"," ");
	var lingo = config.views.wikified.tag;
	var label = null;
	for(var t=0; t<tiddler.tags.length; t++) {
		var tag = store.getTiddler(tiddler.tags[t]);
		if(!tag || !tag.tags.contains("excludeLists")) {
			if(!label)
				label = createTiddlyElement(ul,"li",null,"listTitle",lingo.labelTags.format([tiddler.title]));
			createTagButton(createTiddlyElement(ul,"li"),tiddler.tags[t],tiddler.title);
			if(t<tiddler.tags.length-1)
				createTiddlyText(ul,sep);
		}
	}
	if(!label)
		createTiddlyElement(ul,"li",null,"listTitle",lingo.labelNoTags.format([tiddler.title]));
};

config.macros.tagging.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	params = paramString.parseParams("anon",null,true,false,false);
	var ul = createTiddlyElement(place,"ul");
	var title = getParam(params,"anon","");
	if(title == "" && tiddler instanceof Tiddler)
		title = tiddler.title;
	var sep = getParam(params,"sep"," ");
	ul.setAttribute("title",this.tooltip.format([title]));
	var tagged = store.getTaggedTiddlers(title);
	var prompt = tagged.length == 0 ? this.labelNotTag : this.label;
	createTiddlyElement(ul,"li",null,"listTitle",prompt.format([title,tagged.length]));
	for(var t=0; t<tagged.length; t++) {
		createTiddlyLink(createTiddlyElement(ul,"li"),tagged[t].title,true);
		if(t<tagged.length-1)
			createTiddlyText(ul,sep);
	}
};

config.macros.closeAll.handler = function(place)
{
	createTiddlyButton(place,this.label,this.prompt,this.onClick);
};

config.macros.closeAll.onClick = function(e)
{
	story.closeAllTiddlers();
	return false;
};

config.macros.permaview.handler = function(place)
{
	createTiddlyButton(place,this.label,this.prompt,this.onClick);
};

config.macros.permaview.onClick = function(e)
{
	story.permaView();
	return false;
};

config.macros.saveChanges.handler = function(place,macroName,params)
{
	if(!readOnly)
		createTiddlyButton(place,params[0] || this.label,params[1] || this.prompt,this.onClick,null,null,this.accessKey);
};

config.macros.saveChanges.onClick = function(e)
{
	saveChanges();
	return false;
};

config.macros.slider.onClickSlider = function(ev)
{
	var e = ev || window.event;
	var n = this.nextSibling;
	var cookie = n.getAttribute("cookie");
	var isOpen = n.style.display != "none";
	if(config.options.chkAnimate && anim && typeof Slider == "function")
		anim.startAnimating(new Slider(n,!isOpen,null,"none"));
	else
		n.style.display = isOpen ? "none" : "block";
	config.options[cookie] = !isOpen;
	saveOption(cookie);
	return false;
};

config.macros.slider.createSlider = function(place,cookie,title,tooltip)
{
	var c = cookie || "";
	var btn = createTiddlyButton(place,title,tooltip,this.onClickSlider);
	var panel = createTiddlyElement(null,"div",null,"sliderPanel");
	panel.setAttribute("cookie",c);
	panel.style.display = config.options[c] ? "block" : "none";
	place.appendChild(panel);
	return panel;
};

config.macros.slider.handler = function(place,macroName,params)
{
	var panel = this.createSlider(place,params[0],params[2],params[3]);
	var text = store.getTiddlerText(params[1]);
	panel.setAttribute("refresh","content");
	panel.setAttribute("tiddler",params[1]);
	if(text)
		wikify(text,panel,null,store.getTiddler(params[1]));
};

// <<gradient [[tiddler name]] vert|horiz rgb rgb rgb rgb... >>
config.macros.gradient.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var panel = wikifier ? createTiddlyElement(place,"div",null,"gradient") : place;
	panel.style.position = "relative";
	panel.style.overflow = "hidden";
	panel.style.zIndex = "0";
	if(wikifier) {
		var styles = config.formatterHelpers.inlineCssHelper(wikifier);
		config.formatterHelpers.applyCssHelper(panel,styles);
	}
	params = paramString.parseParams("color");
	var locolors = [], hicolors = [];
	for(var t=2; t<params.length; t++) {
		var c = params[t].value;
		if(params[t].name == "snap") {
			hicolors[hicolors.length-1] = c;
		} else {
			locolors.push(c);
			hicolors.push(c);
		}
	}
	drawGradient(panel,params[1].value != "vert",locolors,hicolors);
	if(wikifier)
		wikifier.subWikify(panel,">>");
	if(document.all) {
		panel.style.height = "100%";
		panel.style.width = "100%";
	}
};

config.macros.message.handler = function(place,macroName,params)
{
	if(params[0]) {
		var names = params[0].split(".");
		var lookupMessage = function(root,nameIndex) {
				if(names[nameIndex] in root) {
					if(nameIndex < names.length-1)
						return (lookupMessage(root[names[nameIndex]],nameIndex+1));
					else
						return root[names[nameIndex]];
				} else
					return null;
			};
		var m = lookupMessage(config,0);
		if(m == null)
			m = lookupMessage(window,0);
		createTiddlyText(place,m.toString().format(params.splice(1)));
	}
};


config.macros.view.depth = 0;
config.macros.view.views = {
	text: function(value,place,params,wikifier,paramString,tiddler) {
		highlightify(value,place,highlightHack,tiddler);
	},
	link: function(value,place,params,wikifier,paramString,tiddler) {
		createTiddlyLink(place,value,true);
	},
	wikified: function(value,place,params,wikifier,paramString,tiddler) {
		if(config.macros.view.depth>50)
			return;
		config.macros.view.depth++;
		if(params[2])
			value=params[2].unescapeLineBreaks().format([value]);
		wikify(value,place,highlightHack,tiddler);
		config.macros.view.depth--;
	},
	date: function(value,place,params,wikifier,paramString,tiddler) {
		value = Date.convertFromYYYYMMDDHHMM(value);
		createTiddlyText(place,value.formatString(params[2] ? params[2] : config.views.wikified.dateFormat));
	}
};

config.macros.view.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	if((tiddler instanceof Tiddler) && params[0]) {
		var value = store.getValue(tiddler,params[0]);
		if(value) {
			var type = params[1] || config.macros.view.defaultView;
			var handler = config.macros.view.views[type];
			if(handler)
				handler(value,place,params,wikifier,paramString,tiddler);
		}
	}
};

config.macros.edit.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var field = params[0];
	var rows = params[1] || 0;
	var defVal = params[2] || '';
	if((tiddler instanceof Tiddler) && field) {
		story.setDirty(tiddler.title,true);
		var e,v;
		if(field != "text" && !rows) {
			e = createTiddlyElement(null,"input",null,null,null,{
				type: "text", edit: field, size: "40", autocomplete: "off"
			});
			e.value = store.getValue(tiddler,field) || defVal;
			place.appendChild(e);
		} else {
			var wrapper1 = createTiddlyElement(null,"fieldset",null,"fieldsetFix");
			var wrapper2 = createTiddlyElement(wrapper1,"div");
			e = createTiddlyElement(wrapper2,"textarea");
			e.value = v = store.getValue(tiddler,field) || defVal;
			rows = rows || 10;
			var lines = v.match(/\n/mg);
			var maxLines = Math.max(parseInt(config.options.txtMaxEditRows),5);
			if(lines != null && lines.length > rows)
				rows = lines.length + 5;
			rows = Math.min(rows,maxLines);
			e.setAttribute("rows",rows);
			e.setAttribute("edit",field);
			place.appendChild(wrapper1);
		}
		if(tiddler.isReadOnly()) {
			e.setAttribute("readOnly","readOnly");
			addClass(e,"readOnly");
		}
		return e;
	}
};

config.macros.tagChooser.onClick = function(ev)
{
	var e = ev || window.event;
	var lingo = config.views.editor.tagChooser;
	var popup = Popup.create(this);
	var tags = store.getTags(this.getAttribute("tags"));
	if(tags.length == 0)
		jQuery("<li/>").text(lingo.popupNone).appendTo(popup);
	for(var t=0; t<tags.length; t++) {
		var tag = createTiddlyButton(createTiddlyElement(popup,"li"),tags[t][0],lingo.tagTooltip.format([tags[t][0]]),config.macros.tagChooser.onTagClick);
		tag.setAttribute("tag",tags[t][0]);
		tag.setAttribute("tiddler",this.getAttribute("tiddler"));
	}
	Popup.show();
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	return false;
};

config.macros.tagChooser.onTagClick = function(ev)
{
	var e = ev || window.event;
	if(e.metaKey || e.ctrlKey) stopEvent(e); //# keep popup open on CTRL-click
	var tag = this.getAttribute("tag");
	var title = this.getAttribute("tiddler");
	if(!readOnly)
		story.setTiddlerTag(title,tag,0);
	return false;
};

config.macros.tagChooser.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	if(tiddler instanceof Tiddler) {
		var lingo = config.views.editor.tagChooser;
		var btn = createTiddlyButton(place,lingo.text,lingo.tooltip,this.onClick);
		btn.setAttribute("tiddler",tiddler.title);
		btn.setAttribute("tags",params[0]);
	}
};

config.macros.refreshDisplay.handler = function(place)
{
	createTiddlyButton(place,this.label,this.prompt,this.onClick);
};

config.macros.refreshDisplay.onClick = function(e)
{
	refreshAll();
	return false;
};

config.macros.annotations.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	var title = tiddler ? tiddler.title : null;
	var a = title ? config.annotations[title] : null;
	if(!tiddler || !title || !a)
		return;
	var text = a.format([title]);
	wikify(text,createTiddlyElement(place,"div",null,"annotation"),null,tiddler);
};

//--
//-- NewTiddler and NewJournal macros
//--

config.macros.newTiddler.createNewTiddlerButton = function(place,title,params,label,prompt,accessKey,newFocus,isJournal)
{
	var tags = [];
	for(var t=1; t<params.length; t++) {
		if((params[t].name == "anon" && t != 1) || (params[t].name == "tag"))
			tags.push(params[t].value);
	}
	label = getParam(params,"label",label);
	prompt = getParam(params,"prompt",prompt);
	accessKey = getParam(params,"accessKey",accessKey);
	newFocus = getParam(params,"focus",newFocus);
	var customFields = getParam(params,"fields","");
	if(!customFields && !store.isShadowTiddler(title))
		customFields = String.encodeHashMap(config.defaultCustomFields);
	var btn = createTiddlyButton(place,label,prompt,this.onClickNewTiddler,null,null,accessKey);
	btn.setAttribute("newTitle",title);
	btn.setAttribute("isJournal",isJournal ? "true" : "false");
	if(tags.length > 0)
		btn.setAttribute("params",tags.join("|"));
	btn.setAttribute("newFocus",newFocus);
	btn.setAttribute("newTemplate",getParam(params,"template",DEFAULT_EDIT_TEMPLATE));
	if(customFields !== "")
		btn.setAttribute("customFields",customFields);
	var text = getParam(params,"text");
	if(text !== undefined)
		btn.setAttribute("newText",text);
	return btn;
};

config.macros.newTiddler.onClickNewTiddler = function()
{
	var title = this.getAttribute("newTitle");
	if(this.getAttribute("isJournal") == "true") {
		title = new Date().formatString(title.trim());
	}
	var params = this.getAttribute("params");
	var tags = params ? params.split("|") : [];
	var focus = this.getAttribute("newFocus");
	var template = this.getAttribute("newTemplate");
	var customFields = this.getAttribute("customFields");
	if(!customFields && !store.isShadowTiddler(title))
		customFields = String.encodeHashMap(config.defaultCustomFields);
	story.displayTiddler(null,title,template,false,null,null);
	var tiddlerElem = story.getTiddler(title);
	if(customFields)
		story.addCustomFields(tiddlerElem,customFields);
	var text = this.getAttribute("newText");
	if(typeof text == "string" && story.getTiddlerField(title,"text"))
		story.getTiddlerField(title,"text").value = text.format([title]);
	for(var t=0;t<tags.length;t++)
		story.setTiddlerTag(title,tags[t],+1);
	story.focusTiddler(title,focus);
	return false;
};

config.macros.newTiddler.handler = function(place,macroName,params,wikifier,paramString)
{
	if(!readOnly) {
		params = paramString.parseParams("anon",null,true,false,false);
		var title = params[1] && params[1].name == "anon" ? params[1].value : this.title;
		title = getParam(params,"title",title);
		this.createNewTiddlerButton(place,title,params,this.label,this.prompt,this.accessKey,"title",false);
	}
};

config.macros.newJournal.handler = function(place,macroName,params,wikifier,paramString)
{
	if(!readOnly) {
		params = paramString.parseParams("anon",null,true,false,false);
		var title = params[1] && params[1].name == "anon" ? params[1].value : config.macros.timeline.dateFormat;
		title = getParam(params,"title",title);
		config.macros.newTiddler.createNewTiddlerButton(place,title,params,this.label,this.prompt,this.accessKey,"text",true);
	}
};

//--
//-- Search macro
//--

config.macros.search.handler = function(place,macroName,params)
{
	var searchTimeout = null;
	var btn = createTiddlyButton(place,this.label,this.prompt,this.onClick,"searchButton");
	var txt = createTiddlyElement(null,"input",null,"txtOptionInput searchField");
	if(params[0]) {
		txt.value = params[0];
	}
	if(config.browser.isSafari) {
		txt.setAttribute("type","search");
		txt.setAttribute("results","5");
	} else {
		txt.setAttribute("type","text");
	}
	place.appendChild(txt);
	txt.onkeyup = this.onKeyPress;
	txt.onfocus = this.onFocus;
	txt.setAttribute("size",this.sizeTextbox);
	txt.setAttribute("accessKey",params[1] || this.accessKey);
	txt.setAttribute("autocomplete","off");
	txt.setAttribute("lastSearchText","");
};

// Global because there's only ever one outstanding incremental search timer
config.macros.search.timeout = null;

config.macros.search.doSearch = function(txt)
{
	if(txt.value.length > 0) {
		story.search(txt.value,config.options.chkCaseSensitiveSearch,config.options.chkRegExpSearch);
		txt.setAttribute("lastSearchText",txt.value);
	}
};

config.macros.search.onClick = function(e)
{
	config.macros.search.doSearch(this.nextSibling);
	return false;
};

config.macros.search.onKeyPress = function(ev)
{
	var me = config.macros.search;
	var e = ev || window.event;
	switch(e.keyCode) {
		case 9: // Tab
			return;
		case 13: // Ctrl-Enter
		case 10: // Ctrl-Enter on IE PC
			me.doSearch(this);
			break;
		case 27: // Escape
			this.value = "";
			clearMessage();
			break;
	}
	if(config.options.chkIncrementalSearch) {
		if(this.value.length > 2) {
			if(this.value != this.getAttribute("lastSearchText")) {
				if(me.timeout) {
					clearTimeout(me.timeout);
				}
				var txt = this;
				me.timeout = setTimeout(function() {me.doSearch(txt);},500);
			}
		} else {
			if(me.timeout) {
				clearTimeout(me.timeout);
			}
		}
	}
};

config.macros.search.onFocus = function(e)
{
	this.select();
};

//--
//-- Tabs macro
//--

config.macros.tabs.handler = function(place,macroName,params)
{
	var cookie = params[0];
	var numTabs = (params.length-1)/3;
	var wrapper = createTiddlyElement(null,"div",null,"tabsetWrapper " + cookie);
	var tabset = createTiddlyElement(wrapper,"div",null,"tabset");
	tabset.setAttribute("cookie",cookie);
	var validTab = false;
	for(var t=0; t<numTabs; t++) {
		var label = params[t*3+1];
		var prompt = params[t*3+2];
		var content = params[t*3+3];
		var tab = createTiddlyButton(tabset,label,prompt,this.onClickTab,"tab tabUnselected");
		createTiddlyElement(tab,"span",null,null," ",{style:"font-size:0pt;line-height:0px"});
		tab.setAttribute("tab",label);
		tab.setAttribute("content",content);
		tab.title = prompt;
		if(config.options[cookie] == label)
			validTab = true;
	}
	if(!validTab)
		config.options[cookie] = params[1];
	place.appendChild(wrapper);
	this.switchTab(tabset,config.options[cookie]);
};

config.macros.tabs.onClickTab = function(e)
{
	config.macros.tabs.switchTab(this.parentNode,this.getAttribute("tab"));
	return false;
};

config.macros.tabs.switchTab = function(tabset,tab)
{
	var cookie = tabset.getAttribute("cookie");
	var theTab = null;
	var nodes = tabset.childNodes;
	for(var t=0; t<nodes.length; t++) {
		if(nodes[t].getAttribute && nodes[t].getAttribute("tab") == tab) {
			theTab = nodes[t];
			theTab.className = "tab tabSelected";
		} else {
			nodes[t].className = "tab tabUnselected";
		}
	}
	if(theTab) {
		if(tabset.nextSibling && tabset.nextSibling.className == "tabContents")
			removeNode(tabset.nextSibling);
		var tabContent = createTiddlyElement(null,"div",null,"tabContents");
		tabset.parentNode.insertBefore(tabContent,tabset.nextSibling);
		var contentTitle = theTab.getAttribute("content");
		wikify(store.getTiddlerText(contentTitle),tabContent,null,store.getTiddler(contentTitle));
		if(cookie) {
			config.options[cookie] = tab;
			saveOption(cookie);
		}
	}
};

//--
//-- Tiddler toolbar
//--

// Create a toolbar command button
config.macros.toolbar.createCommand = function(place,commandName,tiddler,className)
{
	if(typeof commandName != "string") {
		var c = null;
		for(var t in config.commands) {
			if(config.commands[t] == commandName)
				c = t;
		}
		commandName = c;
	}
	if((tiddler instanceof Tiddler) && (typeof commandName == "string")) {
		var command = config.commands[commandName];
		if(command.isEnabled ? command.isEnabled(tiddler) : this.isCommandEnabled(command,tiddler)) {
			var text = command.getText ? command.getText(tiddler) : this.getCommandText(command,tiddler);
			var tooltip = command.getTooltip ? command.getTooltip(tiddler) : this.getCommandTooltip(command,tiddler);
			var cmd;
			switch(command.type) {
			case "popup":
				cmd = this.onClickPopup;
				break;
			case "command":
			default:
				cmd = this.onClickCommand;
				break;
			}
			var btn = createTiddlyButton(null,text,tooltip,cmd);
			btn.setAttribute("commandName",commandName);
			btn.setAttribute("tiddler",tiddler.title);
			addClass(btn,"command_" + commandName);
			if(className)
				addClass(btn,className);
			place.appendChild(btn);
		}
	}
};

config.macros.toolbar.isCommandEnabled = function(command,tiddler)
{
	var title = tiddler.title;
	var ro = tiddler.isReadOnly();
	var shadow = store.isShadowTiddler(title) && !store.tiddlerExists(title);
	return (!ro || (ro && !command.hideReadOnly)) && !(shadow && command.hideShadow);
};

config.macros.toolbar.getCommandText = function(command,tiddler)
{
	return tiddler.isReadOnly() && command.readOnlyText || command.text;
};

config.macros.toolbar.getCommandTooltip = function(command,tiddler)
{
	return tiddler.isReadOnly() && command.readOnlyTooltip || command.tooltip;
};

config.macros.toolbar.onClickCommand = function(ev)
{
	var e = ev || window.event;
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	var command = config.commands[this.getAttribute("commandName")];
	return command.handler(e,this,this.getAttribute("tiddler"));
};

config.macros.toolbar.onClickPopup = function(ev)
{
	var e = ev || window.event;
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	var popup = Popup.create(this);
	var command = config.commands[this.getAttribute("commandName")];
	var title = this.getAttribute("tiddler");
	var tiddler = store.fetchTiddler(title);
	popup.setAttribute("tiddler",title);
	command.handlePopup(popup,title);
	Popup.show();
	return false;
};

// Invoke the first command encountered from a given place that is tagged with a specified class
config.macros.toolbar.invokeCommand = function(place,className,event)
{
	var children = place.getElementsByTagName("a");
	for(var t=0; t<children.length; t++) {
		var c = children[t];
		if(hasClass(c,className) && c.getAttribute && c.getAttribute("commandName")) {
			if(c.onclick instanceof Function)
				c.onclick.call(c,event);
			break;
		}
	}
};

config.macros.toolbar.onClickMore = function(ev)
{
	var e = this.nextSibling;
	e.style.display = "inline";
	this.style.display = "none";
	return false;
};

config.macros.toolbar.onClickLess = function(ev)
{
	var e = this.parentNode;
	var m = e.previousSibling;
	e.style.display = "none";
	m.style.display = "inline";
	return false;
};

config.macros.toolbar.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	for(var t=0; t<params.length; t++) {
		var c = params[t];
		switch(c) {
		case "!":
			createTiddlyText(place,this.separator);
			break;
		case "*":
			createTiddlyElement(place,"br");
			break;
		case "<":
			var btn = createTiddlyButton(place,this.lessLabel,this.lessPrompt,config.macros.toolbar.onClickLess);
			addClass(btn,"lessCommand");
			break;
		case ">":
			var btn = createTiddlyButton(place,this.moreLabel,this.morePrompt,config.macros.toolbar.onClickMore);
			addClass(btn,"moreCommand");
			var e = createTiddlyElement(place,"span",null,"moreCommand");
			e.style.display = "none";
			place = e;
			break;
		default:
			var className = "";
			switch(c.substr(0,1)) {
			case "+":
				className = "defaultCommand";
				c = c.substr(1);
				break;
			case "-":
				className = "cancelCommand";
				c = c.substr(1);
				break;
			}
			if(c in config.commands) {
				this.createCommand(place,c,tiddler,className);
			} else {
				this.customCommand(place,c,wikifier,tiddler);
			}
			break;
		}
	}
};

// Overrideable function to extend toolbar handler
config.macros.toolbar.customCommand = function(place,command,wikifier,tiddler)
{
}

//--
//-- Menu and toolbar commands
//--

config.commands.closeTiddler.handler = function(event,src,title)
{
	if(story.isDirty(title) && !readOnly) {
		if(!confirm(config.commands.cancelTiddler.warning.format([title])))
			return false;
	}
	story.setDirty(title,false);
	story.closeTiddler(title,true);
	return false;
};

config.commands.closeOthers.handler = function(event,src,title)
{
	story.closeAllTiddlers(title);
	return false;
};

config.commands.editTiddler.handler = function(event,src,title)
{
	clearMessage();
	var tiddlerElem = story.getTiddler(title);
	var fields = tiddlerElem.getAttribute("tiddlyFields");
	story.displayTiddler(null,title,DEFAULT_EDIT_TEMPLATE,false,null,fields);
	var e = story.getTiddlerField(title,config.options.txtEditorFocus||"text");
	if(e) {
		setCaretPosition(e,0);
	}
	return false;
};

config.commands.saveTiddler.handler = function(event,src,title)
{
	var newTitle = story.saveTiddler(title,event.shiftKey);
	if(newTitle)
		story.displayTiddler(null,newTitle);
	return false;
};

config.commands.cancelTiddler.handler = function(event,src,title)
{
	if(story.hasChanges(title) && !readOnly) {
		if(!confirm(this.warning.format([title])))
			return false;
	}
	story.setDirty(title,false);
	story.displayTiddler(null,title);
	return false;
};

config.commands.deleteTiddler.handler = function(event,src,title)
{
	var deleteIt = true;
	if(config.options.chkConfirmDelete)
		deleteIt = confirm(this.warning.format([title]));
	if(deleteIt) {
		store.removeTiddler(title);
		story.closeTiddler(title,true);
		autoSaveChanges();
	}
	return false;
};

config.commands.permalink.handler = function(event,src,title)
{
	var t = encodeURIComponent(String.encodeTiddlyLink(title));
	if(window.location.hash != t)
		window.location.hash = t;
	return false;
};

config.commands.references.handlePopup = function(popup,title)
{
	var references = store.getReferringTiddlers(title);
	var c = false;
	for(var r=0; r<references.length; r++) {
		if(references[r].title != title && !references[r].isTagged("excludeLists")) {
			createTiddlyLink(createTiddlyElement(popup,"li"),references[r].title,true);
			c = true;
		}
	}
	if(!c)
		createTiddlyElement(popup,"li",null,"disabled",this.popupNone);
};

config.commands.jump.handlePopup = function(popup,title)
{
	story.forEachTiddler(function(title,element) {
		createTiddlyLink(createTiddlyElement(popup,"li"),title,true,null,false,null,true);
		});
};

config.commands.syncing.handlePopup = function(popup,title)
{
	var me = config.commands.syncing;
	var tiddler = store.fetchTiddler(title);
	if(!tiddler)
		return;
	var serverType = tiddler.getServerType();
	var serverHost = tiddler.fields["server.host"];
	var serverWorkspace = tiddler.fields["server.workspace"];
	if(!serverWorkspace)
		serverWorkspace = "";
	if(serverType) {
		var e = createTiddlyElement(popup,"li",null,"popupMessage");
		e.innerHTML = me.currentlySyncing.format([serverType,serverHost,serverWorkspace]);
	} else {
		createTiddlyElement(popup,"li",null,"popupMessage",me.notCurrentlySyncing);
	}
	if(serverType) {
		createTiddlyElement(createTiddlyElement(popup,"li",null,"listBreak"),"div");
		var btn = createTiddlyButton(createTiddlyElement(popup,"li"),this.captionUnSync,null,me.onChooseServer);
		btn.setAttribute("tiddler",title);
		btn.setAttribute("server.type","");
	}
	createTiddlyElement(createTiddlyElement(popup,"li",null,"listBreak"),"div");
	createTiddlyElement(popup,"li",null,"popupMessage",me.chooseServer);
	var feeds = store.getTaggedTiddlers("systemServer","title");
	for(var t=0; t<feeds.length; t++) {
		var f = feeds[t];
		var feedServerType = store.getTiddlerSlice(f.title,"Type");
		if(!feedServerType)
			feedServerType = "file";
		var feedServerHost = store.getTiddlerSlice(f.title,"URL");
		if(!feedServerHost)
			feedServerHost = "";
		var feedServerWorkspace = store.getTiddlerSlice(f.title,"Workspace");
		if(!feedServerWorkspace)
			feedServerWorkspace = "";
		var caption = f.title;
		if(serverType == feedServerType && serverHost == feedServerHost && serverWorkspace == feedServerWorkspace) {
			caption = me.currServerMarker + caption;
		} else {
			caption = me.notCurrServerMarker + caption;
		}
		btn = createTiddlyButton(createTiddlyElement(popup,"li"),caption,null,me.onChooseServer);
		btn.setAttribute("tiddler",title);
		btn.setAttribute("server.type",feedServerType);
		btn.setAttribute("server.host",feedServerHost);
		btn.setAttribute("server.workspace",feedServerWorkspace);
	}
};

config.commands.syncing.onChooseServer = function(e)
{
	var tiddler = this.getAttribute("tiddler");
	var serverType = this.getAttribute("server.type");
	if(serverType) {
		store.addTiddlerFields(tiddler,{
			"server.type": serverType,
			"server.host": this.getAttribute("server.host"),
			"server.workspace": this.getAttribute("server.workspace")
			});
	} else {
		store.setValue(tiddler,"server",null);
	}
	return false;
};

config.commands.fields.handlePopup = function(popup,title)
{
	var tiddler = store.fetchTiddler(title);
	if(!tiddler)
		return;
	var items = [];
	store.forEachField(tiddler,function(tiddler,fieldName,value){items.push({field:fieldName,value:value});},true);
	items.sort(function(a,b) {return a.field < b.field ? -1 : (a.field == b.field ? 0 : +1);});
	if(items.length > 0)
		ListView.create(popup,items,this.listViewTemplate);
	else
		createTiddlyElement(popup,"div",null,null,this.emptyText);
};

//--
//-- Tiddler() object
//--

function Tiddler(title)
{
	this.title = title;
	this.text = "";
	this.creator = null;
	this.modifier = null;
	this.created = new Date();
	this.modified = this.created;
	this.links = [];
	this.linksUpdated = false;
	this.tags = [];
	this.fields = {};
	return this;
}

Tiddler.prototype.getLinks = function()
{
	if(this.linksUpdated==false)
		this.changed();
	return this.links;
};

// Returns the fields that are inherited in string field:"value" field2:"value2" format
Tiddler.prototype.getInheritedFields = function()
{
	var f = {};
	for(var i in this.fields) {
		if(i=="server.host" || i=="server.workspace" || i=="wikiformat"|| i=="server.type") {
			f[i] = this.fields[i];
		}
	}
	return String.encodeHashMap(f);
};

// Increment the changeCount of a tiddler
Tiddler.prototype.incChangeCount = function()
{
	var c = this.fields['changecount'];
	c = c ? parseInt(c,10) : 0;
	this.fields['changecount'] = String(c+1);
};

// Clear the changeCount of a tiddler
Tiddler.prototype.clearChangeCount = function()
{
	if(this.fields['changecount']) {
		delete this.fields['changecount'];
	}
};

Tiddler.prototype.doNotSave = function()
{
	return this.fields['doNotSave'];
};

// Returns true if the tiddler has been updated since the tiddler was created or downloaded
Tiddler.prototype.isTouched = function()
{
	var changecount = this.fields.changecount || 0;
	return changecount > 0;
};

// Change the text and other attributes of a tiddler
Tiddler.prototype.set = function(title,text,modifier,modified,tags,created,fields,creator)
{
	this.assign(title,text,modifier,modified,tags,created,fields,creator);
	this.changed();
	return this;
};

// Change the text and other attributes of a tiddler without triggered a tiddler.changed() call
Tiddler.prototype.assign = function(title,text,modifier,modified,tags,created,fields,creator)
{
	if(title != undefined)
		this.title = title;
	if(text != undefined)
		this.text = text;
	if(modifier != undefined)
		this.modifier = modifier;
	if(modified != undefined)
		this.modified = modified;
	if(creator != undefined)
		this.creator = creator;
	if(created != undefined)
		this.created = created;
	if(fields != undefined)
		this.fields = fields;
	if(tags != undefined)
		this.tags = (typeof tags == "string") ? tags.readBracketedList() : tags;
	else if(this.tags == undefined)
		this.tags = [];
	return this;
};

// Get the tags for a tiddler as a string (space delimited, using [[brackets]] for tags containing spaces)
Tiddler.prototype.getTags = function()
{
	return String.encodeTiddlyLinkList(this.tags);
};

// Test if a tiddler carries a tag
Tiddler.prototype.isTagged = function(tag)
{
	return this.tags.indexOf(tag) != -1;
};

// Static method to convert "\n" to newlines, "\s" to "\"
Tiddler.unescapeLineBreaks = function(text)
{
	return text ? text.unescapeLineBreaks() : "";
};

// Convert newlines to "\n", "\" to "\s"
Tiddler.prototype.escapeLineBreaks = function()
{
	return this.text.escapeLineBreaks();
};

// Updates the secondary information (like links[] array) after a change to a tiddler
Tiddler.prototype.changed = function()
{
	this.links = [];
	var text = this.text;
	// remove 'quoted' text before scanning tiddler source
	text = text.replace(/\/%((?:.|\n)*?)%\//g,"").
		replace(/\{{3}((?:.|\n)*?)\}{3}/g,"").
		replace(/"""((?:.|\n)*?)"""/g,"").
		replace(/\<nowiki\>((?:.|\n)*?)\<\/nowiki\>/g,"").
		replace(/\<html\>((?:.|\n)*?)\<\/html\>/g,"").
		replace(/\<script((?:.|\n)*?)\<\/script\>/g,"");
	var t = this.autoLinkWikiWords() ? 0 : 1;
	var tiddlerLinkRegExp = t==0 ? config.textPrimitives.tiddlerAnyLinkRegExp : config.textPrimitives.tiddlerForcedLinkRegExp;
	tiddlerLinkRegExp.lastIndex = 0;
	var formatMatch = tiddlerLinkRegExp.exec(text);
	while(formatMatch) {
		var lastIndex = tiddlerLinkRegExp.lastIndex;
		if(t==0 && formatMatch[1] && formatMatch[1] != this.title) {
			// wikiWordLink
			if(formatMatch.index > 0) {
				var preRegExp = new RegExp(config.textPrimitives.unWikiLink+"|"+config.textPrimitives.anyLetter,"mg");
				preRegExp.lastIndex = formatMatch.index-1;
				var preMatch = preRegExp.exec(text);
				if(preMatch.index != formatMatch.index-1)
					this.links.pushUnique(formatMatch[1]);
			} else {
				this.links.pushUnique(formatMatch[1]);
			}
		}
		else if(formatMatch[2-t] && !config.formatterHelpers.isExternalLink(formatMatch[3-t])) // titledBrackettedLink
			this.links.pushUnique(formatMatch[3-t]);
		else if(formatMatch[4-t] && formatMatch[4-t] != this.title) // brackettedLink
			this.links.pushUnique(formatMatch[4-t]);
		tiddlerLinkRegExp.lastIndex = lastIndex;
		formatMatch = tiddlerLinkRegExp.exec(text);
	}
	this.linksUpdated = true;
};

Tiddler.prototype.getSubtitle = function()
{
	var modifier = this.modifier;
	if(!modifier)
		modifier = config.messages.subtitleUnknown;
	var modified = this.modified;
	if(modified)
		modified = modified.toLocaleString();
	else
		modified = config.messages.subtitleUnknown;
	return config.messages.tiddlerLinkTooltip.format([this.title,modifier,modified]);
};

Tiddler.prototype.isReadOnly = function()
{
	return readOnly;
};

Tiddler.prototype.autoLinkWikiWords = function()
{
	return !(this.isTagged("systemConfig") || this.isTagged("excludeMissing"));
};

Tiddler.prototype.getServerType = function()
{
	var serverType = null;
	if(this.fields['server.type'])
		serverType = this.fields['server.type'];
	if(!serverType)
		serverType = this.fields['wikiformat'];
	if(serverType && !config.adaptors[serverType])
		serverType = null;
	return serverType;
};

Tiddler.prototype.getAdaptor = function()
{
	var serverType = this.getServerType();
	return serverType ? new config.adaptors[serverType]() : null;
};

//--
//-- TiddlyWiki instance contains TiddlerS
//--

function TiddlyWiki()
{
	var tiddlers = {}; // Hashmap by name of tiddlers
	this.tiddlersUpdated = false;
	this.namedNotifications = []; // Array of {name:,notify:} of notification functions
	this.notificationLevel = 0;
	this.slices = {}; // map tiddlerName->(map sliceName->sliceValue). Lazy.
	this.clear = function() {
		tiddlers = {};
		this.setDirty(false);
	};
	this.fetchTiddler = function(title) {
		var t = tiddlers[title];
		return t instanceof Tiddler ? t : null;
	};
	this.deleteTiddler = function(title) {
		delete this.slices[title];
		delete tiddlers[title];
	};
	this.addTiddler = function(tiddler) {
		delete this.slices[tiddler.title];
		tiddlers[tiddler.title] = tiddler;
	};
	this.forEachTiddler = function(callback) {
		for(var t in tiddlers) {
			var tiddler = tiddlers[t];
			if(tiddler instanceof Tiddler)
				callback.call(this,t,tiddler);
		}
	};
}

TiddlyWiki.prototype.setDirty = function(dirty)
{
	this.dirty = dirty;
};

TiddlyWiki.prototype.isDirty = function()
{
	return this.dirty;
};

TiddlyWiki.prototype.tiddlerExists = function(title)
{
	var t = this.fetchTiddler(title);
	return t != undefined;
};

TiddlyWiki.prototype.isShadowTiddler = function(title)
{
	return config.shadowTiddlers[title] === undefined ? false : true;
};

TiddlyWiki.prototype.createTiddler = function(title)
{
	var tiddler = this.fetchTiddler(title);
	if(!tiddler) {
		tiddler = new Tiddler(title);
		this.addTiddler(tiddler);
		this.setDirty(true);
	}
	return tiddler;
};

TiddlyWiki.prototype.getTiddler = function(title)
{
	var t = this.fetchTiddler(title);
	if(t != undefined)
		return t;
	else
		return null;
};

TiddlyWiki.prototype.getShadowTiddlerText = function(title)
{
	if(typeof config.shadowTiddlers[title] == "string")
		return config.shadowTiddlers[title];
	else
		return "";
};

// Retrieve tiddler contents
TiddlyWiki.prototype.getTiddlerText = function(title,defaultText)
{
	if(!title)
		return defaultText;
	var pos = title.indexOf(config.textPrimitives.sectionSeparator);
	var section = null;
	if(pos != -1) {
		section = title.substr(pos + config.textPrimitives.sectionSeparator.length);
		title = title.substr(0,pos);
	}
	pos = title.indexOf(config.textPrimitives.sliceSeparator);
	if(pos != -1) {
		var slice = this.getTiddlerSlice(title.substr(0,pos),title.substr(pos + config.textPrimitives.sliceSeparator.length));
		if(slice)
			return slice;
	}
	var tiddler = this.fetchTiddler(title);
	var text = tiddler ? tiddler.text : null;
	if(!tiddler && this.isShadowTiddler(title)) {
		text = this.getShadowTiddlerText(title);
	}
	if(text) {
		if(!section)
			return text;
		var re = new RegExp("(^!{1,6}[ \t]*" + section.escapeRegExp() + "[ \t]*\n)","mg");
		re.lastIndex = 0;
		var match = re.exec(text);
		if(match) {
			var t = text.substr(match.index+match[1].length);
			var re2 = /^!/mg;
			re2.lastIndex = 0;
			match = re2.exec(t); //# search for the next heading
			if(match)
				t = t.substr(0,match.index-1);//# don't include final \n
			return t;
		}
		return defaultText;
	}
	if(defaultText != undefined)
		return defaultText;
	return null;
};

TiddlyWiki.prototype.getRecursiveTiddlerText = function(title,defaultText,depth)
{
	var bracketRegExp = new RegExp("(?:\\[\\[([^\\]]+)\\]\\])","mg");
	var text = this.getTiddlerText(title,null);
	if(text == null)
		return defaultText;
	var textOut = [];
	var lastPos = 0;
	do {
		var match = bracketRegExp.exec(text);
		if(match) {
			textOut.push(text.substr(lastPos,match.index-lastPos));
			if(match[1]) {
				if(depth <= 0)
					textOut.push(match[1]);
				else
					textOut.push(this.getRecursiveTiddlerText(match[1],"",depth-1));
			}
			lastPos = match.index + match[0].length;
		} else {
			textOut.push(text.substr(lastPos));
		}
	} while(match);
	return textOut.join("");
};

//TiddlyWiki.prototype.slicesRE = /(?:^([\'\/]{0,2})~?([\.\w]+)\:\1[\t\x20]*([^\n]+)[\t\x20]*$)|(?:^\|([\'\/]{0,2})~?([\.\w]+)\:?\4\|[\t\x20]*([^\n]+)[\t\x20]*\|$)/gm;
TiddlyWiki.prototype.slicesRE = /(?:^([\'\/]{0,2})~?([\.\w]+)\:\1[\t\x20]*([^\n]*)[\t\x20]*$)|(?:^\|([\'\/]{0,2})~?([\.\w]+)\:?\4\|[\t\x20]*([^\|\n]*)[\t\x20]*\|$)/gm;
// @internal
TiddlyWiki.prototype.calcAllSlices = function(title)
{
	var slices = {};
	var text = this.getTiddlerText(title,"");
	this.slicesRE.lastIndex = 0;
	var m = this.slicesRE.exec(text);
	while(m) {
		if(m[2])
			slices[m[2]] = m[3];
		else
			slices[m[5]] = m[6];
		m = this.slicesRE.exec(text);
	}
	return slices;
};

// Returns the slice of text of the given name
TiddlyWiki.prototype.getTiddlerSlice = function(title,sliceName)
{
	var slices = this.slices[title];
	if(!slices) {
		slices = this.calcAllSlices(title);
		this.slices[title] = slices;
	}
	return slices[sliceName];
};

// Build an hashmap of the specified named slices of a tiddler
TiddlyWiki.prototype.getTiddlerSlices = function(title,sliceNames)
{
	var r = {};
	for(var t=0; t<sliceNames.length; t++) {
		var slice = this.getTiddlerSlice(title,sliceNames[t]);
		if(slice)
			r[sliceNames[t]] = slice;
	}
	return r;
};

TiddlyWiki.prototype.suspendNotifications = function()
{
	this.notificationLevel--;
};

TiddlyWiki.prototype.resumeNotifications = function()
{
	this.notificationLevel++;
};

// Invoke the notification handlers for a particular tiddler
TiddlyWiki.prototype.notify = function(title,doBlanket)
{
	if(!this.notificationLevel) {
		for(var t=0; t<this.namedNotifications.length; t++) {
			var n = this.namedNotifications[t];
			if((n.name == null && doBlanket) || (n.name == title))
				n.notify(title);
		}
	}
};

// Invoke the notification handlers for all tiddlers
TiddlyWiki.prototype.notifyAll = function()
{
	if(!this.notificationLevel) {
		for(var t=0; t<this.namedNotifications.length; t++) {
			var n = this.namedNotifications[t];
			if(n.name)
				n.notify(n.name);
		}
	}
};

// Add a notification handler to a tiddler
TiddlyWiki.prototype.addNotification = function(title,fn)
{
	for(var i=0; i<this.namedNotifications.length; i++) {
		if((this.namedNotifications[i].name == title) && (this.namedNotifications[i].notify == fn))
			return this;
	}
	this.namedNotifications.push({name: title, notify: fn});
	return this;
};

TiddlyWiki.prototype.removeTiddler = function(title)
{
	var tiddler = this.fetchTiddler(title);
	if(tiddler) {
		this.deleteTiddler(title);
		this.notify(title,true);
		this.setDirty(true);
	}
};

// Reset the sync status of a freshly synced tiddler
TiddlyWiki.prototype.resetTiddler = function(title)
{
	var tiddler = this.fetchTiddler(title);
	if(tiddler) {
		tiddler.clearChangeCount();
		this.notify(title,true);
		this.setDirty(true);
	}
};

TiddlyWiki.prototype.setTiddlerTag = function(title,status,tag)
{
	var tiddler = this.fetchTiddler(title);
	if(tiddler) {
		var t = tiddler.tags.indexOf(tag);
		if(t != -1)
			tiddler.tags.splice(t,1);
		if(status)
			tiddler.tags.push(tag);
		tiddler.changed();
		tiddler.incChangeCount();
		this.notify(title,true);
		this.setDirty(true);
	}
};

TiddlyWiki.prototype.addTiddlerFields = function(title,fields)
{
	var tiddler = this.fetchTiddler(title);
	if(!tiddler)
		return;
	merge(tiddler.fields,fields);
	tiddler.changed();
	tiddler.incChangeCount();
	this.notify(title,true);
	this.setDirty(true);
};

// Store tiddler in TiddlyWiki instance
TiddlyWiki.prototype.saveTiddler = function(title,newTitle,newBody,modifier,modified,tags,fields,clearChangeCount,created,creator)
{
	var tiddler;
	if(title instanceof Tiddler) {
		tiddler = title;
		title = tiddler.title;
		newTitle = title;
	} else {
		tiddler = this.fetchTiddler(title);
		if(tiddler) {
			created = created || tiddler.created; // Preserve created date
			creator = creator || tiddler.creator;
			this.deleteTiddler(title);
		} else {
			created = created || modified;
			tiddler = new Tiddler();
		}
		fields = merge({},fields);
		tiddler.set(newTitle,newBody,modifier,modified,tags,created,fields,creator);
	}
	this.addTiddler(tiddler);
	if(clearChangeCount)
		tiddler.clearChangeCount();
	else
		tiddler.incChangeCount();
	if(title != newTitle)
		this.notify(title,true);
	this.notify(newTitle,true);
	this.setDirty(true);
	return tiddler;
};

TiddlyWiki.prototype.incChangeCount = function(title)
{
	var tiddler = this.fetchTiddler(title);
	if(tiddler)
		tiddler.incChangeCount();
};

TiddlyWiki.prototype.getLoader = function()
{
	if(!this.loader)
		this.loader = new TW21Loader();
	return this.loader;
};

TiddlyWiki.prototype.getSaver = function()
{
	if(!this.saver)
		this.saver = new TW21Saver();
	return this.saver;
};

// Return all tiddlers formatted as an HTML string
TiddlyWiki.prototype.allTiddlersAsHtml = function()
{
	return this.getSaver().externalize(store);
};

// Load contents of a TiddlyWiki from an HTML DIV
TiddlyWiki.prototype.loadFromDiv = function(src,idPrefix,noUpdate)
{
	this.idPrefix = idPrefix;
	var storeElem = (typeof src == "string") ? document.getElementById(src) : src;
	if(!storeElem)
		return;
	var tiddlers = this.getLoader().loadTiddlers(this,storeElem.childNodes);
	this.setDirty(false);
	if(!noUpdate) {
		for(var i = 0;i<tiddlers.length; i++)
			tiddlers[i].changed();
	}
	jQuery(document).trigger("loadTiddlers");
};

// Load contents of a TiddlyWiki from a string
// Returns null if there's an error
TiddlyWiki.prototype.importTiddlyWiki = function(text)
{
	var posDiv = locateStoreArea(text);
	if(!posDiv)
		return null;
	var content = "<" + "html><" + "body>" + text.substring(posDiv[0],posDiv[1] + endSaveArea.length) + "<" + "/body><" + "/html>";
	// Create the iframe
	var iframe = document.createElement("iframe");
	iframe.style.display = "none";
	document.body.appendChild(iframe);
	var doc = iframe.document;
	if(iframe.contentDocument)
		doc = iframe.contentDocument; // For NS6
	else if(iframe.contentWindow)
		doc = iframe.contentWindow.document; // For IE5.5 and IE6
	// Put the content in the iframe
	doc.open();
	doc.writeln(content);
	doc.close();
	// Load the content into a TiddlyWiki() object
	var storeArea = doc.getElementById("storeArea");
	this.loadFromDiv(storeArea,"store");
	// Get rid of the iframe
	iframe.parentNode.removeChild(iframe);
	return this;
};

TiddlyWiki.prototype.updateTiddlers = function()
{
	this.tiddlersUpdated = true;
	this.forEachTiddler(function(title,tiddler) {
		tiddler.changed();
	});
};

// Return an array of tiddlers matching a search regular expression
TiddlyWiki.prototype.search = function(searchRegExp,sortField,excludeTag,match)
{
	var candidates = this.reverseLookup("tags",excludeTag,!!match);
	var results = [];
	for(var t=0; t<candidates.length; t++) {
		if((candidates[t].title.search(searchRegExp) != -1) || (candidates[t].text.search(searchRegExp) != -1))
			results.push(candidates[t]);
	}
	if(!sortField)
		sortField = "title";
	results.sort(function(a,b) {return a[sortField] < b[sortField] ? -1 : (a[sortField] == b[sortField] ? 0 : +1);});
	return results;
};

// Returns a list of all tags in use
//   excludeTag - if present, excludes tags that are themselves tagged with excludeTag
// Returns an array of arrays where [tag][0] is the name of the tag and [tag][1] is the number of occurances
TiddlyWiki.prototype.getTags = function(excludeTag)
{
	var results = [];
	this.forEachTiddler(function(title,tiddler) {
		for(var g=0; g<tiddler.tags.length; g++) {
			var tag = tiddler.tags[g];
			var n = true;
			for(var c=0; c<results.length; c++) {
				if(results[c][0] == tag) {
					n = false;
					results[c][1]++;
				}
			}
			if(n && excludeTag) {
				var t = this.fetchTiddler(tag);
				if(t && t.isTagged(excludeTag))
					n = false;
			}
			if(n)
				results.push([tag,1]);
		}
	});
	results.sort(function(a,b) {return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : (a[0].toLowerCase() == b[0].toLowerCase() ? 0 : +1);});
	return results;
};

// Return an array of the tiddlers that are tagged with a given tag
TiddlyWiki.prototype.getTaggedTiddlers = function(tag,sortField)
{
	return this.reverseLookup("tags",tag,true,sortField);
};

TiddlyWiki.prototype.getValueTiddlers = function(field,value,sortField)
{
	return this.reverseLookup(field,value,true,sortField);
};

// Return an array of the tiddlers that link to a given tiddler
TiddlyWiki.prototype.getReferringTiddlers = function(title,unusedParameter,sortField)
{
	if(!this.tiddlersUpdated)
		this.updateTiddlers();
	return this.reverseLookup("links",title,true,sortField);
};

// Return an array of the tiddlers that do or do not have a specified entry in the specified storage array (ie, "links" or "tags")
// lookupMatch == true to match tiddlers, false to exclude tiddlers
TiddlyWiki.prototype.reverseLookup = function(lookupField,lookupValue,lookupMatch,sortField)
{
	var results = [];
	this.forEachTiddler(function(title,tiddler) {
		var f = !lookupMatch;
		var values;
		if(["links", "tags"].contains(lookupField)) {
			values = tiddler[lookupField];
		} else {
			values = tiddler.fields[lookupField] ? [tiddler.fields[lookupField]] : [];
		}
		for(var lookup=0; lookup<values.length; lookup++) {
			if(values[lookup] == lookupValue)
				f = lookupMatch;
		}
		if(f)
			results.push(tiddler);
	});
	if(!sortField)
		sortField = "title";
	return this.sortTiddlers(results,sortField);
};

// Return the tiddlers as a sorted array
TiddlyWiki.prototype.getTiddlers = function(field,excludeTag)
{
	var results = [];
	this.forEachTiddler(function(title,tiddler) {
		if(excludeTag == undefined || !tiddler.isTagged(excludeTag))
			results.push(tiddler);
	});
	if(field)
		results.sort(function(a,b) {return a[field] < b[field] ? -1 : (a[field] == b[field] ? 0 : +1);});
	return results;
};

// Return array of names of tiddlers that are referred to but not defined
TiddlyWiki.prototype.getMissingLinks = function(sortField)
{
	if(!this.tiddlersUpdated)
		this.updateTiddlers();
	var results = [];
	this.forEachTiddler(function (title,tiddler) {
		if(tiddler.isTagged("excludeMissing") || tiddler.isTagged("systemConfig"))
			return;
		for(var n=0; n<tiddler.links.length;n++) {
			var link = tiddler.links[n];
			if(this.getTiddlerText(link,null) == null && !this.isShadowTiddler(link) && !config.macros[link])
				results.pushUnique(link);
		}
	});
	results.sort();
	return results;
};

// Return an array of names of tiddlers that are defined but not referred to
TiddlyWiki.prototype.getOrphans = function()
{
	var results = [];
	this.forEachTiddler(function (title,tiddler) {
		if(this.getReferringTiddlers(title).length == 0 && !tiddler.isTagged("excludeLists"))
			results.push(title);
	});
	results.sort();
	return results;
};

// Return an array of names of all the shadow tiddlers
TiddlyWiki.prototype.getShadowed = function()
{
	var results = [];
	for(var t in config.shadowTiddlers) {
		if(this.isShadowTiddler(t))
			results.push(t);
	}
	results.sort();
	return results;
};

// Return an array of tiddlers that have been touched since they were downloaded or created
TiddlyWiki.prototype.getTouched = function()
{
	var results = [];
	this.forEachTiddler(function(title,tiddler) {
		if(tiddler.isTouched())
			results.push(tiddler);
		});
	results.sort();
	return results;
};

// Resolves a Tiddler reference or tiddler title into a Tiddler object, or null if it doesn't exist
TiddlyWiki.prototype.resolveTiddler = function(tiddler)
{
	var t = (typeof tiddler == "string") ? this.getTiddler(tiddler) : tiddler;
	return t instanceof Tiddler ? t : null;
};

// Sort a list of tiddlers
TiddlyWiki.prototype.sortTiddlers = function(tiddlers,field)
{
	var asc = +1;
	switch(field.substr(0,1)) {
	case "-":
		asc = -1;
		// Note: this fall-through is intentional
		/*jsl:fallthru*/
	case "+":
		field = field.substr(1);
		break;
	}
	if(TiddlyWiki.standardFieldAccess[field]) {
		if(field=="title") {
			tiddlers.sort(function(a,b) {return a[field].toLowerCase() < b[field].toLowerCase() ? -asc : (a[field].toLowerCase() == b[field].toLowerCase() ? 0 : asc);});
		} else {
			tiddlers.sort(function(a,b) {return a[field] < b[field] ? -asc : (a[field] == b[field] ? 0 : asc);});
		}
	} else {
		tiddlers.sort(function(a,b) {return a.fields[field] < b.fields[field] ? -asc : (a.fields[field] == b.fields[field] ? 0 : +asc);});
	}
	return tiddlers;
};

//--
//-- Filter a list of tiddlers
//--

config.filters = {
	tiddler: function(results,match) {
		var title = match[1]||match[4];
		var tiddler = this.fetchTiddler(title);
		if(tiddler) {
			results.pushUnique(tiddler);
		} else if(this.isShadowTiddler(title)) {
			tiddler = new Tiddler();
			tiddler.set(title,this.getTiddlerText(title));
			results.pushUnique(tiddler);
		} else {
			results.pushUnique(new Tiddler(title));
		}
		return results;
	},
	tag: function(results,match) {
		var matched = this.getTaggedTiddlers(match[3]);
		for(var m=0; m<matched.length; m++) {
			results.pushUnique(matched[m]);
		}
		return results;
	},
	sort: function(results,match) {
		return this.sortTiddlers(results,match[3]);
	},
	limit: function(results,match) {
		return results.slice(0,parseInt(match[3],10));
	},
	field: function(results,match) {
		var matched = this.getValueTiddlers(match[2],match[3]);
		for (var m = 0; m < matched.length; m++) {
			results.pushUnique(matched[m]);
		}
		return results;
	}
};

// Filter a list of tiddlers
TiddlyWiki.prototype.filterTiddlers = function(filter)
{
	var re = /([^\s\[\]]+)|(?:\[([ \w\.\-]+)\[([^\]]+)\]\])|(?:\[\[([^\]]+)\]\])/mg;

	var results = [];
	if(filter) {
		var match = re.exec(filter);
		while(match) {
			var handler = (match[1]||match[4])?'tiddler':config.filters[match[2]]?match[2]:'field';
			results = config.filters[handler].call(this,results,match);
			match = re.exec(filter);
		}
	}
	return results;
};
// Returns true if path is a valid field name (path),
// i.e. a sequence of identifiers, separated by "."
TiddlyWiki.isValidFieldName = function(name)
{
	var match = /[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*/.exec(name);
	return match && (match[0] == name);
};

// Throws an exception when name is not a valid field name.
TiddlyWiki.checkFieldName = function(name)
{
	if(!TiddlyWiki.isValidFieldName(name))
		throw config.messages.invalidFieldName.format([name]);
};

function StringFieldAccess(n,readOnly)
{
	this.set = readOnly ?
			function(t,v) {if(v != t[n]) throw config.messages.fieldCannotBeChanged.format([n]);} :
			function(t,v) {if(v != t[n]) {t[n] = v; return true;}};
	this.get = function(t) {return t[n];};
}

function DateFieldAccess(n)
{
	this.set = function(t,v) {
		var d = v instanceof Date ? v : Date.convertFromYYYYMMDDHHMM(v);
		if(d != t[n]) {
			t[n] = d; return true;
		}
	};
	this.get = function(t) {return t[n].convertToYYYYMMDDHHMM();};
}

function LinksFieldAccess(n)
{
	this.set = function(t,v) {
		var s = (typeof v == "string") ? v.readBracketedList() : v;
		if(s.toString() != t[n].toString()) {
			t[n] = s; return true;
		}
	};
	this.get = function(t) {return String.encodeTiddlyLinkList(t[n]);};
}

TiddlyWiki.standardFieldAccess = {
	// The set functions return true when setting the data has changed the value.
	"title":    new StringFieldAccess("title",true),
	// Handle the "tiddler" field name as the title
	"tiddler":  new StringFieldAccess("title",true),
	"text":     new StringFieldAccess("text"),
	"modifier": new StringFieldAccess("modifier"),
	"modified": new DateFieldAccess("modified"),
	"creator":  new StringFieldAccess("creator"),
	"created":  new DateFieldAccess("created"),
	"tags":     new LinksFieldAccess("tags")
};

TiddlyWiki.isStandardField = function(name)
{
	return TiddlyWiki.standardFieldAccess[name] != undefined;
};

// Sets the value of the given field of the tiddler to the value.
// Setting an ExtendedField's value to null or undefined removes the field.
// Setting a namespace to undefined removes all fields of that namespace.
// The fieldName is case-insensitive.
// All values will be converted to a string value.
TiddlyWiki.prototype.setValue = function(tiddler,fieldName,value)
{
	TiddlyWiki.checkFieldName(fieldName);
	var t = this.resolveTiddler(tiddler);
	if(!t)
		return;
	fieldName = fieldName.toLowerCase();
	var isRemove = (value === undefined) || (value === null);
	var accessor = TiddlyWiki.standardFieldAccess[fieldName];
	if(accessor) {
		if(isRemove)
			// don't remove StandardFields
			return;
		var h = TiddlyWiki.standardFieldAccess[fieldName];
		if(!h.set(t,value))
			return;
	} else {
		var oldValue = t.fields[fieldName];
		if(isRemove) {
			if(oldValue !== undefined) {
				// deletes a single field
				delete t.fields[fieldName];
			} else {
				// no concrete value is defined for the fieldName
				// so we guess this is a namespace path.
				// delete all fields in a namespace
				var re = new RegExp("^"+fieldName+"\\.");
				var dirty = false;
				for(var n in t.fields) {
					if(n.match(re)) {
						delete t.fields[n];
						dirty = true;
					}
				}
				if(!dirty)
					return;
			}
		} else {
			// the "normal" set case. value is defined (not null/undefined)
			// For convenience provide a nicer conversion Date->String
			value = value instanceof Date ? value.convertToYYYYMMDDHHMMSSMMM() : String(value);
			if(oldValue == value)
				return;
			t.fields[fieldName] = value;
		}
	}
	// When we are here the tiddler/store really was changed.
	this.notify(t.title,true);
	if(!fieldName.match(/^temp\./))
		this.setDirty(true);
};

// Returns the value of the given field of the tiddler.
// The fieldName is case-insensitive.
// Will only return String values (or undefined).
TiddlyWiki.prototype.getValue = function(tiddler,fieldName)
{
	var t = this.resolveTiddler(tiddler);
	if(!t)
		return undefined;
	fieldName = fieldName.toLowerCase();
	var accessor = TiddlyWiki.standardFieldAccess[fieldName];
	if(accessor) {
		return accessor.get(t);
	}
	return t.fields[fieldName];
};

// Calls the callback function for every field in the tiddler.
// When callback function returns a non-false value the iteration stops
// and that value is returned.
// The order of the fields is not defined.
// @param callback a function(tiddler,fieldName,value).
TiddlyWiki.prototype.forEachField = function(tiddler,callback,onlyExtendedFields)
{
	var t = this.resolveTiddler(tiddler);
	if(!t)
		return undefined;
	var n,result;
	for(n in t.fields) {
		result = callback(t,n,t.fields[n]);
		if(result)
			return result;
		}
	if(onlyExtendedFields)
		return undefined;
	for(n in TiddlyWiki.standardFieldAccess) {
		if(n == "tiddler")
			// even though the "title" field can also be referenced through the name "tiddler"
			// we only visit this field once.
			continue;
		result = callback(t,n,TiddlyWiki.standardFieldAccess[n].get(t));
		if(result)
			return result;
	}
	return undefined;
};

//--
//-- Story functions
//--

function Story(containerId,idPrefix)
{
	this.container = containerId;
	this.idPrefix = idPrefix;
	this.highlightRegExp = null;
	this.tiddlerId = function(title) {
		var id = this.idPrefix + title;
		return id==this.container ? this.idPrefix + "_" + title : id;
	};
	this.containerId = function() {
		return this.container;
	};
}

Story.prototype.getTiddler = function(title)
{
	return document.getElementById(this.tiddlerId(title));
};

Story.prototype.getContainer = function()
{
	return document.getElementById(this.containerId());
};

Story.prototype.forEachTiddler = function(fn)
{
	var place = this.getContainer();
	if(!place)
		return;
	var e = place.firstChild;
	while(e) {
		var n = e.nextSibling;
		var title = e.getAttribute("tiddler");
		fn.call(this,title,e);
		e = n;
	}
};

Story.prototype.displayDefaultTiddlers = function()
{
	this.displayTiddlers(null,store.filterTiddlers(store.getTiddlerText("DefaultTiddlers")));
};

Story.prototype.displayTiddlers = function(srcElement,titles,template,animate,unused,customFields,toggle)
{
	for(var t = titles.length-1;t>=0;t--)
		this.displayTiddler(srcElement,titles[t],template,animate,unused,customFields);
};

Story.prototype.displayTiddler = function(srcElement,tiddler,template,animate,unused,customFields,toggle,animationSrc)
{
	var title = (tiddler instanceof Tiddler) ? tiddler.title : tiddler;
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem) {
		if(toggle) {
			if(tiddlerElem.getAttribute("dirty") != "true")
				this.closeTiddler(title,true);
		} else {
			this.refreshTiddler(title,template,false,customFields);
		}
	} else {
		var place = this.getContainer();
		var before = this.positionTiddler(srcElement);
		tiddlerElem = this.createTiddler(place,before,title,template,customFields);
	}
	if(animationSrc && typeof animationSrc !== "string") {
		srcElement = animationSrc;
	}
	if(srcElement && typeof srcElement !== "string") {
		if(config.options.chkAnimate && (animate == undefined || animate == true) && anim && typeof Zoomer == "function" && typeof Scroller == "function")
			anim.startAnimating(new Zoomer(title,srcElement,tiddlerElem),new Scroller(tiddlerElem));
		else
			window.scrollTo(0,ensureVisible(tiddlerElem));
	}
	return tiddlerElem;
};

Story.prototype.positionTiddler = function(srcElement)
{
	var place = this.getContainer();
	var before = null;
	if(typeof srcElement == "string") {
		switch(srcElement) {
		case "top":
			before = place.firstChild;
			break;
		case "bottom":
			before = null;
			break;
		}
	} else {
		var after = this.findContainingTiddler(srcElement);
		if(after == null) {
			before = place.firstChild;
		} else if(after.nextSibling) {
			before = after.nextSibling;
			if(before.nodeType != 1)
				before = null;
		}
	}
	return before;
};

Story.prototype.createTiddler = function(place,before,title,template,customFields)
{
	var tiddlerElem = createTiddlyElement(null,"div",this.tiddlerId(title),"tiddler");
	tiddlerElem.setAttribute("refresh","tiddler");
	if(customFields)
		tiddlerElem.setAttribute("tiddlyFields",customFields);
	place.insertBefore(tiddlerElem,before);
	var defaultText = null;
	if(!store.tiddlerExists(title) && !store.isShadowTiddler(title))
		defaultText = this.loadMissingTiddler(title,customFields);
	this.refreshTiddler(title,template,false,customFields,defaultText);
	return tiddlerElem;
};

Story.prototype.loadMissingTiddler = function(title,fields,callback)
{
	var getTiddlerCallback = function(context)
	{
		if(context.status) {
			var t = context.tiddler;
			if(!t.created)
				t.created = new Date();
			if(!t.modified)
				t.modified = t.created;
			context.tiddler = store.saveTiddler(t.title,t.title,t.text,t.modifier,t.modified,t.tags,t.fields,true,t.created,t.creator);
			autoSaveChanges();
		} else {
			story.refreshTiddler(context.title,null,true);
		}
		context.adaptor.close();
		if(callback) {
			callback(context);
		}
	};
	var tiddler = new Tiddler(title);
	tiddler.fields = typeof fields == "string" ? fields.decodeHashMap() : fields||{};
	var context = {serverType:tiddler.getServerType()};
	if(!context.serverType)
		return;
	context.host = tiddler.fields['server.host'];
	context.workspace = tiddler.fields['server.workspace'];
	var adaptor = new config.adaptors[context.serverType];
	adaptor.getTiddler(title,context,null,getTiddlerCallback);
	return config.messages.loadingMissingTiddler.format([title,context.serverType,context.host,context.workspace]);
};

Story.prototype.chooseTemplateForTiddler = function(title,template)
{
	if(!template)
		template = DEFAULT_VIEW_TEMPLATE;
	if(template == DEFAULT_VIEW_TEMPLATE || template == DEFAULT_EDIT_TEMPLATE)
		template = config.tiddlerTemplates[template];
	return template;
};

Story.prototype.getTemplateForTiddler = function(title,template,tiddler)
{
	return store.getRecursiveTiddlerText(template,null,10);
};

Story.prototype.refreshTiddler = function(title,template,force,customFields,defaultText)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem) {
		if(tiddlerElem.getAttribute("dirty") == "true" && !force)
			return tiddlerElem;
		template = this.chooseTemplateForTiddler(title,template);
		var currTemplate = tiddlerElem.getAttribute("template");
		if((template != currTemplate) || force) {
			var tiddler = store.getTiddler(title);
			if(!tiddler) {
				tiddler = new Tiddler();
				if(store.isShadowTiddler(title)) {
					var tags = [];
					tiddler.set(title,store.getTiddlerText(title),config.views.wikified.shadowModifier,version.date,tags,version.date);
				} else {
					var text = template=="EditTemplate" ?
								config.views.editor.defaultText.format([title]) :
								config.views.wikified.defaultText.format([title]);
					text = defaultText || text;
					var fields = customFields ? customFields.decodeHashMap() : null;
					tiddler.set(title,text,config.views.wikified.defaultModifier,version.date,[],version.date,fields);
				}
			}
			tiddlerElem.setAttribute("tags",tiddler.tags.join(" "));
			tiddlerElem.setAttribute("tiddler",title);
			tiddlerElem.setAttribute("template",template);
			tiddlerElem.onmouseover = this.onTiddlerMouseOver;
			tiddlerElem.onmouseout = this.onTiddlerMouseOut;
			tiddlerElem.ondblclick = this.onTiddlerDblClick;
			tiddlerElem[window.event?"onkeydown":"onkeypress"] = this.onTiddlerKeyPress;
			tiddlerElem.innerHTML = this.getTemplateForTiddler(title,template,tiddler);
			applyHtmlMacros(tiddlerElem,tiddler);
			if(store.getTaggedTiddlers(title).length > 0)
				addClass(tiddlerElem,"isTag");
			else
				removeClass(tiddlerElem,"isTag");
			if(store.tiddlerExists(title)) {
				removeClass(tiddlerElem,"shadow");
				removeClass(tiddlerElem,"missing");
			} else {
				addClass(tiddlerElem, store.isShadowTiddler(title) ? "shadow" : "missing");
			}
			if(customFields)
				this.addCustomFields(tiddlerElem,customFields);
			forceReflow();
		}
	}
	return tiddlerElem;
};

Story.prototype.addCustomFields = function(place,customFields)
{
	var fields = customFields.decodeHashMap();
	var w = createTiddlyElement(place,"div",null,"customFields");
	w.style.display = "none";
	for(var t in fields) {
		var e = document.createElement("input");
		e.setAttribute("type","text");
		e.setAttribute("value",fields[t]);
		w.appendChild(e);
		e.setAttribute("edit",t);
	}
};

Story.prototype.refreshAllTiddlers = function(force)
{
	var e = this.getContainer().firstChild;
	while(e) {
		var template = e.getAttribute("template");
		if(template && e.getAttribute("dirty") != "true") {
			this.refreshTiddler(e.getAttribute("tiddler"),force ? null : template,true);
		}
		e = e.nextSibling;
	}
};

Story.prototype.onTiddlerMouseOver = function(e)
{
	addClass(this, "selected");
};

Story.prototype.onTiddlerMouseOut = function(e)
{
	removeClass(this,"selected");
};

Story.prototype.onTiddlerDblClick = function(ev)
{
	var e = ev || window.event;
	var target = resolveTarget(e);
	if(target && target.nodeName.toLowerCase() != "input" && target.nodeName.toLowerCase() != "textarea") {
		if(document.selection && document.selection.empty)
			document.selection.empty();
		config.macros.toolbar.invokeCommand(this,"defaultCommand",e);
		e.cancelBubble = true;
		if(e.stopPropagation) e.stopPropagation();
		return true;
	}
	return false;
};

Story.prototype.onTiddlerKeyPress = function(ev)
{
	var e = ev || window.event;
	clearMessage();
	var consume = false;
	var title = this.getAttribute("tiddler");
	var target = resolveTarget(e);
	switch(e.keyCode) {
	case 9: // Tab
		var ed = story.getTiddlerField(title,"text");
		if(target.tagName.toLowerCase() == "input" && ed.value==config.views.editor.defaultText.format([title])) {
			// moving from input field and editor still contains default text, so select it
			ed.focus();
			ed.select();
			consume = true;
		}
		if(config.options.chkInsertTabs && target.tagName.toLowerCase() == "textarea") {
			replaceSelection(target,String.fromCharCode(9));
			consume = true;
		}
		if(config.isOpera) {
			target.onblur = function() {
				this.focus();
				this.onblur = null;
			};
		}
		break;
	case 13: // Ctrl-Enter
	case 10: // Ctrl-Enter on IE PC
	case 77: // Ctrl-Enter is "M" on some platforms
		if(e.ctrlKey) {
			blurElement(this);
			config.macros.toolbar.invokeCommand(this,"defaultCommand",e);
			consume = true;
		}
		break;
	case 27: // Escape
		blurElement(this);
		config.macros.toolbar.invokeCommand(this,"cancelCommand",e);
		consume = true;
		break;
	}
	e.cancelBubble = consume;
	if(consume) {
		if(e.stopPropagation) e.stopPropagation(); // Stop Propagation
		e.returnValue = true; // Cancel The Event in IE
		if(e.preventDefault ) e.preventDefault(); // Cancel The Event in Moz
	}
	return !consume;
};

Story.prototype.getTiddlerField = function(title,field)
{
	var tiddlerElem = this.getTiddler(title);
	var e = null;
	if(tiddlerElem) {
		var children = tiddlerElem.getElementsByTagName("*");
		for(var t=0; t<children.length; t++) {
			var c = children[t];
			if(c.tagName.toLowerCase() == "input" || c.tagName.toLowerCase() == "textarea") {
				if(!e)
					e = c;
				if(c.getAttribute("edit") == field)
					e = c;
			}
		}
	}
	return e;
};

Story.prototype.focusTiddler = function(title,field)
{
	var e = this.getTiddlerField(title,field);
	if(e) {
		e.focus();
		e.select();
	}
};

Story.prototype.blurTiddler = function(title)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem && tiddlerElem.focus && tiddlerElem.blur) {
		tiddlerElem.focus();
		tiddlerElem.blur();
	}
};

Story.prototype.setTiddlerField = function(title,tag,mode,field)
{
	var c = this.getTiddlerField(title,field);
	var tags = c.value.readBracketedList();
	tags.setItem(tag,mode);
	c.value = String.encodeTiddlyLinkList(tags);
};

Story.prototype.setTiddlerTag = function(title,tag,mode)
{
	this.setTiddlerField(title,tag,mode,"tags");
};

Story.prototype.closeTiddler = function(title,animate,unused)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem) {
		clearMessage();
		this.scrubTiddler(tiddlerElem);
		if(config.options.chkAnimate && animate && anim && typeof Slider == "function")
			anim.startAnimating(new Slider(tiddlerElem,false,null,"all"));
		else {
			removeNode(tiddlerElem);
			forceReflow();
		}
	}
};

Story.prototype.scrubTiddler = function(tiddlerElem)
{
	tiddlerElem.id = null;
};

Story.prototype.setDirty = function(title,dirty)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem)
		tiddlerElem.setAttribute("dirty",dirty ? "true" : "false");
};

Story.prototype.isDirty = function(title)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem)
		return tiddlerElem.getAttribute("dirty") == "true";
	return null;
};

Story.prototype.areAnyDirty = function()
{
	var r = false;
	this.forEachTiddler(function(title,element) {
		if(this.isDirty(title))
			r = true;
	});
	return r;
};

Story.prototype.closeAllTiddlers = function(exclude)
{
	clearMessage();
	this.forEachTiddler(function(title,element) {
		if((title != exclude) && element.getAttribute("dirty") != "true")
			this.closeTiddler(title);
	});
	window.scrollTo(0,ensureVisible(this.container));
};

Story.prototype.isEmpty = function()
{
	var place = this.getContainer();
	return place && place.firstChild == null;
};

Story.prototype.search = function(text,useCaseSensitive,useRegExp)
{
	this.closeAllTiddlers();
	highlightHack = new RegExp(useRegExp ? text : text.escapeRegExp(),useCaseSensitive ? "mg" : "img");
	var matches = store.search(highlightHack,"title","excludeSearch");
	this.displayTiddlers(null,matches);
	highlightHack = null;
	var q = useRegExp ? "/" : "'";
	if(matches.length > 0)
		displayMessage(config.macros.search.successMsg.format([matches.length.toString(),q + text + q]));
	else
		displayMessage(config.macros.search.failureMsg.format([q + text + q]));
};

Story.prototype.findContainingTiddler = function(e)
{
	while(e && !hasClass(e,"tiddler")) {
		e = hasClass(e,"popup") && Popup.stack[0] ? Popup.stack[0].root : e.parentNode;
	}
	return e;
};

Story.prototype.gatherSaveFields = function(e,fields)
{
	if(e && e.getAttribute) {
		var f = e.getAttribute("edit");
		if(f)
			fields[f] = e.value.replace(/\r/mg,"");
		if(e.hasChildNodes()) {
			var c = e.childNodes;
			for(var t=0; t<c.length; t++)
				this.gatherSaveFields(c[t],fields);
		}
	}
};

Story.prototype.hasChanges = function(title)
{
	var e = this.getTiddler(title);
	if(e) {
		var fields = {};
		this.gatherSaveFields(e,fields);
		if(store.fetchTiddler(title)) {
			for(var n in fields) {
				if(store.getValue(title,n) != fields[n]) //# tiddler changed
					return true;
			}
		} else {
			if(store.isShadowTiddler(title) && store.getShadowTiddlerText(title) == fields.text) { //# not checking for title or tags
				return false;
			} else { //# changed shadow or new tiddler
				return true;
			}
		}
	}
	return false;
};

Story.prototype.saveTiddler = function(title,minorUpdate)
{
	var tiddlerElem = this.getTiddler(title);
	if(tiddlerElem) {
		var fields = {};
		this.gatherSaveFields(tiddlerElem,fields);
		var newTitle = fields.title || title;
		if(!store.tiddlerExists(newTitle)) {
			newTitle = newTitle.trim();
			var creator = config.options.txtUserName;
		}
		if(store.tiddlerExists(newTitle) && newTitle != title) {
			if(!confirm(config.messages.overwriteWarning.format([newTitle.toString()])))
				return null;
		}
		if(newTitle != title)
			this.closeTiddler(newTitle,false);
		tiddlerElem.id = this.tiddlerId(newTitle);
		tiddlerElem.setAttribute("tiddler",newTitle);
		tiddlerElem.setAttribute("template",DEFAULT_VIEW_TEMPLATE);
		tiddlerElem.setAttribute("dirty","false");
		if(config.options.chkForceMinorUpdate)
			minorUpdate = !minorUpdate;
		if(!store.tiddlerExists(newTitle))
			minorUpdate = false;
		var newDate = new Date();
		if(store.tiddlerExists(title)) {
			var t = store.fetchTiddler(title);
			var extendedFields = t.fields;
			creator = t.creator;
		} else {
			extendedFields = merge({},config.defaultCustomFields);
		}
		for(var n in fields) {
			if(!TiddlyWiki.isStandardField(n))
				extendedFields[n] = fields[n];
		}
		var tiddler = store.saveTiddler(title,newTitle,fields.text,minorUpdate ? undefined : config.options.txtUserName,minorUpdate ? undefined : newDate,fields.tags,extendedFields,null,null,creator);
		autoSaveChanges(null,[tiddler]);
		return newTitle;
	}
	return null;
};

Story.prototype.permaView = function()
{
	var links = [];
	this.forEachTiddler(function(title,element) {
		links.push(String.encodeTiddlyLink(title));
	});
	var t = encodeURIComponent(links.join(" "));
	if(t == "")
		t = "#";
	if(window.location.hash != t)
		window.location.hash = t;
};

Story.prototype.switchTheme = function(theme)
{
	if(safeMode)
		return;

	var isAvailable = function(title) {
		var s = title ? title.indexOf(config.textPrimitives.sectionSeparator) : -1;
		if(s!=-1)
			title = title.substr(0,s);
		return store.tiddlerExists(title) || store.isShadowTiddler(title);
	};

	var getSlice = function(theme,slice) {
		var r;
		if(readOnly)
			r = store.getTiddlerSlice(theme,slice+"ReadOnly") || store.getTiddlerSlice(theme,"Web"+slice);
		r = r || store.getTiddlerSlice(theme,slice);
		if(r && r.indexOf(config.textPrimitives.sectionSeparator)==0)
			r = theme + r;
		return isAvailable(r) ? r : slice;
	};

	var replaceNotification = function(i,name,theme,slice) {
		var newName = getSlice(theme,slice);
		if(name!=newName && store.namedNotifications[i].name==name) {
			store.namedNotifications[i].name = newName;
			return newName;
		}
		return name;
	};

	var pt = config.refresherData.pageTemplate;
	var vi = DEFAULT_VIEW_TEMPLATE;
	var vt = config.tiddlerTemplates[vi];
	var ei = DEFAULT_EDIT_TEMPLATE;
	var et = config.tiddlerTemplates[ei];

	for(var i=0; i<config.notifyTiddlers.length; i++) {
		var name = config.notifyTiddlers[i].name;
		switch(name) {
		case "PageTemplate":
			config.refresherData.pageTemplate = replaceNotification(i,config.refresherData.pageTemplate,theme,name);
			break;
		case "StyleSheet":
			removeStyleSheet(config.refresherData.styleSheet);
			config.refresherData.styleSheet = replaceNotification(i,config.refresherData.styleSheet,theme,name);
			break;
		case "ColorPalette":
			config.refresherData.colorPalette = replaceNotification(i,config.refresherData.colorPalette,theme,name);
			break;
		default:
			break;
		}
	}
	config.tiddlerTemplates[vi] = getSlice(theme,"ViewTemplate");
	config.tiddlerTemplates[ei] = getSlice(theme,"EditTemplate");
	if(!startingUp) {
		if(config.refresherData.pageTemplate!=pt || config.tiddlerTemplates[vi]!=vt || config.tiddlerTemplates[ei]!=et) {
			refreshAll();
			this.refreshAllTiddlers(true);
		} else {
			setStylesheet(store.getRecursiveTiddlerText(config.refresherData.styleSheet,"",10),config.refreshers.styleSheet);
		}
		config.options.txtTheme = theme;
		saveOption("txtTheme");
	}
};

//--
//-- Backstage
//--

var backstage = {
	area: null,
	toolbar: null,
	button: null,
	showButton: null,
	hideButton: null,
	cloak: null,
	panel: null,
	panelBody: null,
	panelFooter: null,
	currTabName: null,
	currTabElem: null,
	content: null,

	init: function() {
		var cmb = config.messages.backstage;
		this.area = document.getElementById("backstageArea");
		this.toolbar = jQuery("#backstageToolbar").empty()[0];
		this.button = jQuery("#backstageButton").empty()[0];
		this.button.style.display = "block";
		var t = cmb.open.text + " " + glyph("bentArrowLeft");
		this.showButton = createTiddlyButton(this.button,t,cmb.open.tooltip,
						function(e) {backstage.show(); return false;},null,"backstageShow");
		t = glyph("bentArrowRight") + " " + cmb.close.text;
		this.hideButton = createTiddlyButton(this.button,t,cmb.close.tooltip,
						function(e) {backstage.hide(); return false;},null,"backstageHide");
		this.cloak = document.getElementById("backstageCloak");
		this.panel = document.getElementById("backstagePanel");
		this.panelFooter = createTiddlyElement(this.panel,"div",null,"backstagePanelFooter");
		this.panelBody = createTiddlyElement(this.panel,"div",null,"backstagePanelBody");
		this.cloak.onmousedown = function(e) {backstage.switchTab(null);};
		createTiddlyText(this.toolbar,cmb.prompt);
		for(t=0; t<config.backstageTasks.length; t++) {
			var taskName = config.backstageTasks[t];
			var task = config.tasks[taskName];
			var handler = task.action ? this.onClickCommand : this.onClickTab;
			var text = task.text + (task.action ? "" : glyph("downTriangle"));
			var btn = createTiddlyButton(this.toolbar,text,task.tooltip,handler,"backstageTab");
			addClass(btn,task.action ? "backstageAction" : "backstageTask");
			btn.setAttribute("task", taskName);
			}
		this.content = document.getElementById("contentWrapper");
		if(config.options.chkBackstage)
			this.show();
		else
			this.hide();
	},

	isVisible: function() {
		return this.area ? this.area.style.display == "block" : false;
	},

	show: function() {
		this.area.style.display = "block";
		if(anim && config.options.chkAnimate) {
			backstage.toolbar.style.left = findWindowWidth() + "px";
			var p = [{style: "left", start: findWindowWidth(), end: 0, template: "%0px"}];
			anim.startAnimating(new Morpher(backstage.toolbar,config.animDuration,p));
		} else {
			backstage.area.style.left = "0px";
		}
		jQuery(this.showButton).hide();
		jQuery(this.hideButton).show();
		config.options.chkBackstage = true;
		saveOption("chkBackstage");
		addClass(this.content,"backstageVisible");
	},

	hide: function() {
		if(this.currTabElem) {
			this.switchTab(null);
		} else {
			backstage.toolbar.style.left = "0px";
			if(anim && config.options.chkAnimate) {
				var p = [{style: "left", start: 0, end: findWindowWidth(), template: "%0px"}];
				var c = function(element,properties) {backstage.area.style.display = "none";};
				anim.startAnimating(new Morpher(backstage.toolbar,config.animDuration,p,c));
			} else {
				this.area.style.display = "none";
			}
			this.showButton.style.display = "block";
			this.hideButton.style.display = "none";
			config.options.chkBackstage = false;
			saveOption("chkBackstage");
			removeClass(this.content, "backstageVisible");
		}
	},

	onClickCommand: function(e) {
		var task = config.tasks[this.getAttribute("task")];
		if(task.action) {
			backstage.switchTab(null);
			task.action();
		}
		return false;
	},

	onClickTab: function(e) {
		backstage.switchTab(this.getAttribute("task"));
		return false;
	},

	// Switch to a given tab, or none if null is passed
	switchTab: function(tabName) {
		var tabElem = null;
		var e = this.toolbar.firstChild;
		while(e)
			{
			if(e.getAttribute && e.getAttribute("task") == tabName)
				tabElem = e;
			e = e.nextSibling;
			}
		if(tabName == backstage.currTabName) {
			backstage.hidePanel();
			return;
		}
		if(backstage.currTabElem) {
			removeClass(this.currTabElem, "backstageSelTab");
		}
		if(tabElem && tabName) {
			backstage.preparePanel();
			addClass(tabElem,"backstageSelTab");
			var task = config.tasks[tabName];
			wikify(task.content,backstage.panelBody,null,null);
			backstage.showPanel();
		} else if(backstage.currTabElem) {
			backstage.hidePanel();
		}
		backstage.currTabName = tabName;
		backstage.currTabElem = tabElem;
	},

	isPanelVisible: function() {
		return backstage.panel ? backstage.panel.style.display == "block" : false;
	},

	preparePanel: function() {
		backstage.cloak.style.height = findWindowHeight() + "px";
		backstage.cloak.style.display = "block";
		removeChildren(backstage.panelBody);
		return backstage.panelBody;
	},

	showPanel: function() {
		backstage.panel.style.display = "block";
		if(anim && config.options.chkAnimate) {
			backstage.panel.style.top = (-backstage.panel.offsetHeight) + "px";
			var p = [{style: "top", start: -backstage.panel.offsetHeight, end: 0, template: "%0px"}];
			anim.startAnimating(new Morpher(backstage.panel,config.animDuration,p),new Scroller(backstage.panel,false));
		} else {
			backstage.panel.style.top = "0px";
		}
		return backstage.panelBody;
	},

	hidePanel: function() {
		if(backstage.currTabElem)
			removeClass(backstage.currTabElem, "backstageSelTab");
		backstage.currTabElem = null;
		backstage.currTabName = null;
		if(anim && config.options.chkAnimate) {
			var p = [
				{style: "top", start: 0, end: -(backstage.panel.offsetHeight), template: "%0px"},
				{style: "display", atEnd: "none"}
			];
			var c = function(element,properties) {backstage.cloak.style.display = "none";};
			anim.startAnimating(new Morpher(backstage.panel,config.animDuration,p,c));
		} else {
			jQuery([backstage.panel,backstage.cloak]).hide();
		}
	}
};

config.macros.backstage = {};

config.macros.backstage.handler = function(place,macroName,params)
{
	var backstageTask = config.tasks[params[0]];
	if(backstageTask)
		createTiddlyButton(place,backstageTask.text,backstageTask.tooltip,function(e) {backstage.switchTab(params[0]); return false;});
};

//--
//-- ImportTiddlers macro
//--

config.macros.importTiddlers.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	if(readOnly) {
		createTiddlyElement(place,"div",null,"marked",this.readOnlyWarning);
		return;
	}
	var w = new Wizard();
	w.createWizard(place,this.wizardTitle);
	this.restart(w);
};

config.macros.importTiddlers.onCancel = function(e)
{
	var wizard = new Wizard(this);
	var place = wizard.clear();
	config.macros.importTiddlers.restart(wizard);
	return false;
};

config.macros.importTiddlers.onClose = function(e)
{
	backstage.hidePanel();
	return false;
};

config.macros.importTiddlers.restart = function(wizard)
{
	var me = config.macros.importTiddlers;
	wizard.addStep(this.step1Title,this.step1Html);
	var s = wizard.getElement("selTypes");
	for(var t in config.adaptors) {
		var e = createTiddlyElement(s,"option",null,null,config.adaptors[t].serverLabel ? config.adaptors[t].serverLabel : t);
		e.value = t;
	}
	if(config.defaultAdaptor)
		s.value = config.defaultAdaptor;
	s = wizard.getElement("selFeeds");
	var feeds = this.getFeeds();
	for(t in feeds) {
		e = createTiddlyElement(s,"option",null,null,t);
		e.value = t;
	}
	wizard.setValue("feeds",feeds);
	s.onchange = me.onFeedChange;
	var fileInput = wizard.getElement("txtBrowse");
	fileInput.onchange = me.onBrowseChange;
	fileInput.onkeyup = me.onBrowseChange;
	wizard.setButtons([{caption: this.openLabel, tooltip: this.openPrompt, onClick: me.onOpen}]);
	wizard.formElem.action = "javascript:;";
	wizard.formElem.onsubmit = function() {
		if(!this.txtPath || this.txtPath.value.length) //# check for manually entered path in first step
			this.lastChild.firstChild.onclick();
	};
};

config.macros.importTiddlers.getFeeds = function()
{
	var feeds = {};
	var tagged = store.getTaggedTiddlers("systemServer","title");
	for(var t=0; t<tagged.length; t++) {
		var title = tagged[t].title;
		var serverType = store.getTiddlerSlice(title,"Type");
		if(!serverType)
			serverType = "file";
		feeds[title] = {title: title,
						url: store.getTiddlerSlice(title,"URL"),
						workspace: store.getTiddlerSlice(title,"Workspace"),
						workspaceList: store.getTiddlerSlice(title,"WorkspaceList"),
						tiddlerFilter: store.getTiddlerSlice(title,"TiddlerFilter"),
						serverType: serverType,
						description: store.getTiddlerSlice(title,"Description")};
	}
	return feeds;
};

config.macros.importTiddlers.onFeedChange = function(e)
{
	var wizard = new Wizard(this);
	var selTypes = wizard.getElement("selTypes");
	var fileInput = wizard.getElement("txtPath");
	var feeds = wizard.getValue("feeds");
	var f = feeds[this.value];
	if(f) {
		selTypes.value = f.serverType;
		fileInput.value = f.url;
		wizard.setValue("feedName",f.serverType);
		wizard.setValue("feedHost",f.url);
		wizard.setValue("feedWorkspace",f.workspace);
		wizard.setValue("feedWorkspaceList",f.workspaceList);
		wizard.setValue("feedTiddlerFilter",f.tiddlerFilter);
	}
	return false;
};

config.macros.importTiddlers.onBrowseChange = function(e)
{
	var wizard = new Wizard(this);
	if(this.files && this.files[0]) {
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead");
		} catch (ex) {
			showException(ex);
		}
	}
	var fileInput = wizard.getElement("txtPath");
	fileInput.value = config.macros.importTiddlers.getURLFromLocalPath(this.value);
	var serverType = wizard.getElement("selTypes");
	serverType.value = "file";
	return true;
};

config.macros.importTiddlers.getURLFromLocalPath = function(v)
{
	if(!v || !v.length)
		return v;
	v = v.replace(/\\/g,"/"); // use "/" for cross-platform consistency
	var u;
	var t = v.split(":");
	var p = t[1] || t[0]; // remove drive letter (if any)
	if(t[1] && (t[0] == "http" || t[0] == "https" || t[0] == "file")) {
		u = v;
	} else if(p.substr(0,1)=="/") {
		u = document.location.protocol + "//" + document.location.hostname + (t[1] ? "/" : "") + v;
	} else {
		var c = document.location.href.replace(/\\/g,"/");
		var pos = c.lastIndexOf("/");
		if(pos!=-1)
			c = c.substr(0,pos); // remove filename
		u = c + "/" + p;
	}
	return u;
};

config.macros.importTiddlers.onOpen = function(e)
{
	var me = config.macros.importTiddlers;
	var wizard = new Wizard(this);
	var fileInput = wizard.getElement("txtPath");
	var url = fileInput.value;
	var serverType = wizard.getElement("selTypes").value || config.defaultAdaptor;
	var adaptor = new config.adaptors[serverType]();
	wizard.setValue("adaptor",adaptor);
	wizard.setValue("serverType",serverType);
	wizard.setValue("host",url);
	var ret = adaptor.openHost(url,null,wizard,me.onOpenHost);
	if(ret !== true)
		displayMessage(ret);
	wizard.setButtons([{caption: me.cancelLabel, tooltip: me.cancelPrompt, onClick: me.onCancel}],me.statusOpenHost);
	return false;
};

config.macros.importTiddlers.onOpenHost = function(context,wizard)
{
	var me = config.macros.importTiddlers;
	var adaptor = wizard.getValue("adaptor");
	if(context.status !== true)
		displayMessage("Error in importTiddlers.onOpenHost: " + context.statusText);
	var ret = adaptor.getWorkspaceList(context,wizard,me.onGetWorkspaceList);
	if(ret !== true)
		displayMessage(ret);
	wizard.setButtons([{caption: me.cancelLabel, tooltip: me.cancelPrompt, onClick: me.onCancel}],me.statusGetWorkspaceList);
};

config.macros.importTiddlers.onGetWorkspaceList = function(context,wizard)
{
	var me = config.macros.importTiddlers;
	if(context.status !== true)
		displayMessage("Error in importTiddlers.onGetWorkspaceList: " + context.statusText);
	wizard.setValue("context",context);
	var workspace = wizard.getValue("feedWorkspace");
	if(!workspace && context.workspaces.length==1)
		workspace = context.workspaces[0].title;
	if(workspace) {
		var ret = context.adaptor.openWorkspace(workspace,context,wizard,me.onOpenWorkspace);
		if(ret !== true)
			displayMessage(ret);
		wizard.setValue("workspace",workspace);
		wizard.setButtons([{caption: me.cancelLabel, tooltip: me.cancelPrompt, onClick: me.onCancel}],me.statusOpenWorkspace);
		return;
	}
	wizard.addStep(me.step2Title,me.step2Html);
	var s = wizard.getElement("selWorkspace");
	s.onchange = me.onWorkspaceChange;
	for(var t=0; t<context.workspaces.length; t++) {
		var e = createTiddlyElement(s,"option",null,null,context.workspaces[t].title);
		e.value = context.workspaces[t].title;
	}
	var workspaceList = wizard.getValue("feedWorkspaceList");
	if(workspaceList) {
		var list = workspaceList.parseParams("workspace",null,false,true);
		for(var n=1; n<list.length; n++) {
			if(context.workspaces.findByField("title",list[n].value) == null) {
				e = createTiddlyElement(s,"option",null,null,list[n].value);
				e.value = list[n].value;
			}
		}
	}
	if(workspace) {
		t = wizard.getElement("txtWorkspace");
		t.value = workspace;
	}
	wizard.setButtons([{caption: me.openLabel, tooltip: me.openPrompt, onClick: me.onChooseWorkspace}]);
};

config.macros.importTiddlers.onWorkspaceChange = function(e)
{
	var wizard = new Wizard(this);
	var t = wizard.getElement("txtWorkspace");
	t.value = this.value;
	this.selectedIndex = 0;
	return false;
};

config.macros.importTiddlers.onChooseWorkspace = function(e)
{
	var me = config.macros.importTiddlers;
	var wizard = new Wizard(this);
	var adaptor = wizard.getValue("adaptor");
	var workspace = wizard.getElement("txtWorkspace").value;
	wizard.setValue("workspace",workspace);
	var context = wizard.getValue("context");
	var ret = adaptor.openWorkspace(workspace,context,wizard,me.onOpenWorkspace);
	if(ret !== true)
		displayMessage(ret);
	wizard.setButtons([{caption: me.cancelLabel, tooltip: me.cancelPrompt, onClick: me.onCancel}],me.statusOpenWorkspace);
	return false;
};

config.macros.importTiddlers.onOpenWorkspace = function(context,wizard)
{
	var me = config.macros.importTiddlers;
	if(context.status !== true)
		displayMessage("Error in importTiddlers.onOpenWorkspace: " + context.statusText);
	var adaptor = wizard.getValue("adaptor");
	var ret = adaptor.getTiddlerList(context,wizard,me.onGetTiddlerList,wizard.getValue("feedTiddlerFilter"));
	if(ret !== true)
		displayMessage(ret);
	wizard.setButtons([{caption: me.cancelLabel, tooltip: me.cancelPrompt, onClick: me.onCancel}],me.statusGetTiddlerList);
};

config.macros.importTiddlers.onGetTiddlerList = function(context,wizard)
{
	var me = config.macros.importTiddlers;
	if(context.status !== true) {
		wizard.setButtons([{caption: me.cancelLabel, tooltip: me.cancelPrompt, onClick: me.onCancel}],me.errorGettingTiddlerList);
		return;
	}
	// Extract data for the listview
	var listedTiddlers = [];
	if(context.tiddlers) {
		for(var n=0; n<context.tiddlers.length; n++) {
			var tiddler = context.tiddlers[n];
			listedTiddlers.push({
				title: tiddler.title,
				modified: tiddler.modified,
				modifier: tiddler.modifier,
				text: tiddler.text ? wikifyPlainText(tiddler.text,100) : "",
				tags: tiddler.tags,
				size: tiddler.text ? tiddler.text.length : 0,
				tiddler: tiddler
			});
		}
	}
	listedTiddlers.sort(function(a,b) {return a.title < b.title ? -1 : (a.title == b.title ? 0 : +1);});
	// Display the listview
	wizard.addStep(me.step3Title,me.step3Html);
	var markList = wizard.getElement("markList");
	var listWrapper = document.createElement("div");
	markList.parentNode.insertBefore(listWrapper,markList);
	var listView = ListView.create(listWrapper,listedTiddlers,me.listViewTemplate);
	wizard.setValue("listView",listView);
	wizard.setValue("context",context);
	var txtSaveTiddler = wizard.getElement("txtSaveTiddler");
	txtSaveTiddler.value = me.generateSystemServerName(wizard);
	wizard.setButtons([
			{caption: me.cancelLabel, tooltip: me.cancelPrompt, onClick: me.onCancel},
			{caption: me.importLabel, tooltip: me.importPrompt, onClick: me.doImport}
		]);
};

config.macros.importTiddlers.generateSystemServerName = function(wizard)
{
	var serverType = wizard.getValue("serverType");
	var host = wizard.getValue("host");
	var workspace = wizard.getValue("workspace");
	var pattern = config.macros.importTiddlers[workspace ? "systemServerNamePattern" : "systemServerNamePatternNoWorkspace"];
	return pattern.format([serverType,host,workspace]);
};

config.macros.importTiddlers.saveServerTiddler = function(wizard)
{
	var me = config.macros.importTiddlers;
	var txtSaveTiddler = wizard.getElement("txtSaveTiddler").value;
	if(store.tiddlerExists(txtSaveTiddler)) {
		if(!confirm(me.confirmOverwriteSaveTiddler.format([txtSaveTiddler])))
			return;
		store.suspendNotifications();
		store.removeTiddler(txtSaveTiddler);
		store.resumeNotifications();
	}
	var serverType = wizard.getValue("serverType");
	var host = wizard.getValue("host");
	var workspace = wizard.getValue("workspace");
	var text = me.serverSaveTemplate.format([serverType,host,workspace]);
	store.saveTiddler(txtSaveTiddler,txtSaveTiddler,text,me.serverSaveModifier,new Date(),["systemServer"]);
};

config.macros.importTiddlers.doImport = function(e)
{
	var me = config.macros.importTiddlers;
	var wizard = new Wizard(this);
	if(wizard.getElement("chkSave").checked)
		me.saveServerTiddler(wizard);
	var chkSync = wizard.getElement("chkSync").checked;
	wizard.setValue("sync",chkSync);
	var listView = wizard.getValue("listView");
	var rowNames = ListView.getSelectedRows(listView);
	var adaptor = wizard.getValue("adaptor");
	var overwrite = [];
	var t;
	for(t=0; t<rowNames.length; t++) {
		if(store.tiddlerExists(rowNames[t]))
			overwrite.push(rowNames[t]);
	}
	if(overwrite.length > 0) {
		if(!confirm(me.confirmOverwriteText.format([overwrite.join(", ")])))
			return false;
	}
	wizard.addStep(me.step4Title.format([rowNames.length]),me.step4Html);
	for(t=0; t<rowNames.length; t++) {
		var link = document.createElement("div");
		createTiddlyLink(link,rowNames[t],true);
		var place = wizard.getElement("markReport");
		place.parentNode.insertBefore(link,place);
	}
	wizard.setValue("remainingImports",rowNames.length);
	wizard.setButtons([
			{caption: me.cancelLabel, tooltip: me.cancelPrompt, onClick: me.onCancel}
		],me.statusDoingImport);
	var wizardContext = wizard.getValue("context");
	var tiddlers = wizardContext ? wizardContext.tiddlers : [];
	for(t=0; t<rowNames.length; t++) {
		var context = {
			allowSynchronous:true,
			tiddler:tiddlers[tiddlers.findByField("title",rowNames[t])]
		};
		adaptor.getTiddler(rowNames[t],context,wizard,me.onGetTiddler);
	}
	return false;
};

config.macros.importTiddlers.onGetTiddler = function(context,wizard)
{
	var me = config.macros.importTiddlers;
	if(!context.status)
		displayMessage("Error in importTiddlers.onGetTiddler: " + context.statusText);
	var tiddler = context.tiddler;
	store.suspendNotifications();
	store.saveTiddler(tiddler.title, tiddler.title, tiddler.text, tiddler.modifier, tiddler.modified, tiddler.tags, tiddler.fields, true, tiddler.created);
	if(!wizard.getValue("sync")) {
		store.setValue(tiddler.title,'server',null);
	}
	store.resumeNotifications();
	if(!context.isSynchronous)
		store.notify(tiddler.title,true);
	var remainingImports = wizard.getValue("remainingImports")-1;
	wizard.setValue("remainingImports",remainingImports);
	if(remainingImports == 0) {
		if(context.isSynchronous) {
			store.notifyAll();
			refreshDisplay();
		}
		wizard.setButtons([
				{caption: me.doneLabel, tooltip: me.donePrompt, onClick: me.onClose}
			],me.statusDoneImport);
		autoSaveChanges();
	}
};

//--
//-- Upgrade macro
//--

config.macros.upgrade.handler = function(place)
{
	var w = new Wizard();
	w.createWizard(place,this.wizardTitle);
	w.addStep(this.step1Title,this.step1Html.format([this.source,this.source]));
	w.setButtons([{caption: this.upgradeLabel, tooltip: this.upgradePrompt, onClick: this.onClickUpgrade}]);
};

config.macros.upgrade.onClickUpgrade = function(e)
{
	var me = config.macros.upgrade;
	var w = new Wizard(this);
	if(window.location.protocol != "file:") {
		alert(me.errorCantUpgrade);
		return false;
	}
	if(story.areAnyDirty() || store.isDirty()) {
		alert(me.errorNotSaved);
		return false;
	}
	var localPath = getLocalPath(document.location.toString());
	var backupPath = getBackupPath(localPath,me.backupExtension);
	w.setValue("backupPath",backupPath);
	w.setButtons([],me.statusPreparingBackup);
	var original = loadOriginal(localPath);
	w.setButtons([],me.statusSavingBackup);
	var backup = copyFile(backupPath,localPath);
	if(!backup)
		backup = saveFile(backupPath,original);
	if(!backup) {
		w.setButtons([],me.errorSavingBackup);
		alert(me.errorSavingBackup);
		return false;
	}
	w.setButtons([],me.statusLoadingCore);
	var load = loadRemoteFile(me.source,me.onLoadCore,w);
	if(typeof load == "string") {
		w.setButtons([],me.errorLoadingCore);
		alert(me.errorLoadingCore);
		return false;
	}
	return false;
};

config.macros.upgrade.onLoadCore = function(status,params,responseText,url,xhr)
{
	var me = config.macros.upgrade;
	var w = params;
	var errMsg;
	if(!status)
		errMsg = me.errorLoadingCore;
	var newVer = me.extractVersion(responseText);
	if(!newVer)
		errMsg = me.errorCoreFormat;
	if(errMsg) {
		w.setButtons([],errMsg);
		alert(errMsg);
		return;
	}
	var onStartUpgrade = function(e) {
		w.setButtons([],me.statusSavingCore);
		var localPath = getLocalPath(document.location.toString());
		saveFile(localPath,responseText);
		w.setButtons([],me.statusReloadingCore);
		var backupPath = w.getValue("backupPath");
		var newLoc = document.location.toString() + "?time=" + new Date().convertToYYYYMMDDHHMM() + "#upgrade:[[" + encodeURI(backupPath) + "]]";
		window.setTimeout(function () {window.location = newLoc;},10);
	};
	var step2 = [me.step2Html_downgrade,me.step2Html_restore,me.step2Html_upgrade][compareVersions(version,newVer) + 1];
	w.addStep(me.step2Title,step2.format([formatVersion(newVer),formatVersion(version)]));
	w.setButtons([{caption: me.startLabel, tooltip: me.startPrompt, onClick: onStartUpgrade},{caption: me.cancelLabel, tooltip: me.cancelPrompt, onClick: me.onCancel}]);
};

config.macros.upgrade.onCancel = function(e)
{
	var me = config.macros.upgrade;
	var w = new Wizard(this);
	w.addStep(me.step3Title,me.step3Html);
	w.setButtons([]);
	return false;
};

config.macros.upgrade.extractVersion = function(upgradeFile)
{
	var re = /^var version = \{title: "([^"]+)", major: (\d+), minor: (\d+), revision: (\d+)(, beta: (\d+)){0,1}, date: new Date\("([^"]+)"\)/mg;
	var m = re.exec(upgradeFile);
	return m ? {title: m[1], major: m[2], minor: m[3], revision: m[4], beta: m[6], date: new Date(m[7])} : null;
};

function upgradeFrom(path)
{
	var importStore = new TiddlyWiki();
	var tw = loadFile(path);
	if(window.netscape !== undefined)
		tw = convertUTF8ToUnicode(tw);
	importStore.importTiddlyWiki(tw);
	importStore.forEachTiddler(function(title,tiddler) {
		if(!store.getTiddler(title)) {
			store.addTiddler(tiddler);
		}
	});
	refreshDisplay();
	saveChanges(); //# To create appropriate Markup* sections
	alert(config.messages.upgradeDone.format([formatVersion()]));
	window.location = window.location.toString().substr(0,window.location.toString().lastIndexOf("?"));
}

//--
//-- Sync macro
//--

// Synchronisation handlers
config.syncers = {};

// Sync state.
var currSync = null;

// sync macro
config.macros.sync.handler = function(place,macroName,params,wikifier,paramString,tiddler)
{
	if(!wikifier.isStatic)
		this.startSync(place);
};

config.macros.sync.cancelSync = function()
{
	currSync = null;
};

config.macros.sync.startSync = function(place)
{
	if(currSync)
		config.macros.sync.cancelSync();
	currSync = {};
	currSync.syncList = this.getSyncableTiddlers();
	currSync.syncTasks = this.createSyncTasks(currSync.syncList);
	this.preProcessSyncableTiddlers(currSync.syncList);
	var wizard = new Wizard();
	currSync.wizard = wizard;
	wizard.createWizard(place,this.wizardTitle);
	wizard.addStep(this.step1Title,this.step1Html);
	var markList = wizard.getElement("markList");
	var listWrapper = document.createElement("div");
	markList.parentNode.insertBefore(listWrapper,markList);
	currSync.listView = ListView.create(listWrapper,currSync.syncList,this.listViewTemplate);
	this.processSyncableTiddlers(currSync.syncList);
	wizard.setButtons([{caption: this.syncLabel, tooltip: this.syncPrompt, onClick: this.doSync}]);
};

config.macros.sync.getSyncableTiddlers = function()
{
	var list = [];
	store.forEachTiddler(function(title,tiddler) {
		var syncItem = {};
		syncItem.serverType = tiddler.getServerType();
		syncItem.serverHost = tiddler.fields['server.host'];
		if(syncItem.serverType && syncItem.serverHost) {
			syncItem.adaptor = new config.adaptors[syncItem.serverType];
			syncItem.serverHost = syncItem.adaptor.fullHostName(syncItem.serverHost);
			syncItem.serverWorkspace = tiddler.fields['server.workspace'];
			syncItem.tiddler = tiddler;
			syncItem.title = tiddler.title;
			syncItem.isTouched = tiddler.isTouched();
			syncItem.selected = syncItem.isTouched;
			syncItem.syncStatus = config.macros.sync.syncStatusList[syncItem.isTouched ? "changedLocally" : "none"];
			syncItem.status = syncItem.syncStatus.text;
			list.push(syncItem);
		}
		});
	list.sort(function(a,b) {return a.title < b.title ? -1 : (a.title == b.title ? 0 : +1);});
	return list;
};

config.macros.sync.preProcessSyncableTiddlers = function(syncList)
{
	for(var i=0; i<syncList.length; i++) {
		var si = syncList[i];
		si.serverUrl = si.adaptor.generateTiddlerInfo(si.tiddler).uri;
	}
};

config.macros.sync.processSyncableTiddlers = function(syncList)
{
	for(var i=0; i<syncList.length; i++) {
		var si = syncList[i];
		if(si.syncStatus.display)
			si.rowElement.style.display = si.syncStatus.display;
		if(si.syncStatus.className)
			si.rowElement.className = si.syncStatus.className;
	}
};

config.macros.sync.createSyncTasks = function(syncList)
{
	var syncTasks = [];
	for(var i=0; i<syncList.length; i++) {
		var si = syncList[i];
		var r = null;
		for(var j=0; j<syncTasks.length; j++) {
			var cst = syncTasks[j];
			if(si.serverType == cst.serverType && si.serverHost == cst.serverHost && si.serverWorkspace == cst.serverWorkspace)
				r = cst;
		}
		if(r) {
			si.syncTask = r;
			r.syncItems.push(si);
		} else {
			si.syncTask = this.createSyncTask(si);
			syncTasks.push(si.syncTask);
		}
	}
	return syncTasks;
};

config.macros.sync.createSyncTask = function(syncItem)
{
	var st = {};
	st.serverType = syncItem.serverType;
	st.serverHost = syncItem.serverHost;
	st.serverWorkspace = syncItem.serverWorkspace;
	st.syncItems = [syncItem];

	var openWorkspaceCallback = function(context,syncItems) {
		if(context.status) {
			context.adaptor.getTiddlerList(context,syncItems,getTiddlerListCallback);
			return true;
		}
		displayMessage(context.statusText);
		return false;
	};

	var getTiddlerListCallback = function(context,sycnItems) {
		var me = config.macros.sync;
		if(!context.status) {
			displayMessage(context.statusText);
			return false;
		}
		syncItems = context.userParams;
		var tiddlers = context.tiddlers;
		for(var i=0; i<syncItems.length; i++) {
			var si = syncItems[i];
			var f = tiddlers.findByField("title",si.title);
			if(f !== null) {
				if(tiddlers[f].fields['server.page.revision'] > si.tiddler.fields['server.page.revision']) {
					si.syncStatus = me.syncStatusList[si.isTouched ? 'changedBoth' : 'changedServer'];
				}
			} else {
				si.syncStatus = me.syncStatusList.notFound;
			}
			me.updateSyncStatus(si);
		}
		return true;
	};
	var context = {host:st.serverHost,workspace:st.serverWorkspace};
	syncItem.adaptor.openHost(st.serverHost);
	syncItem.adaptor.openWorkspace(st.serverWorkspace,context,st.syncItems,openWorkspaceCallback);
	return st;
};

config.macros.sync.updateSyncStatus = function(syncItem)
{
	var e = syncItem.colElements["status"];
	removeChildren(e);
	createTiddlyText(e,syncItem.syncStatus.text);
	syncItem.rowElement.style.display = syncItem.syncStatus.display;
	if(syncItem.syncStatus.className)
		syncItem.rowElement.className = syncItem.syncStatus.className;
};

config.macros.sync.doSync = function(e)
{
	var me = config.macros.sync;
	var getTiddlerCallback = function(context,syncItem) {
		if(syncItem) {
			var tiddler = context.tiddler;
			store.saveTiddler(tiddler.title,tiddler.title,tiddler.text,tiddler.modifier,tiddler.modified,tiddler.tags,tiddler.fields,true,tiddler.created);
			syncItem.syncStatus = me.syncStatusList.gotFromServer;
			me.updateSyncStatus(syncItem);
		}
	};
	var putTiddlerCallback = function(context,syncItem) {
		if(syncItem) {
			store.resetTiddler(context.title);
			syncItem.syncStatus = me.syncStatusList.putToServer;
			me.updateSyncStatus(syncItem);
		}
	};

	var rowNames = ListView.getSelectedRows(currSync.listView);
	var sl = me.syncStatusList;
	for(var i=0; i<currSync.syncList.length; i++) {
		var si = currSync.syncList[i];
		if(rowNames.indexOf(si.title) != -1) {
			var errorMsg = "Error in doSync: ";
			try {
				var r = true;
				switch(si.syncStatus) {
				case sl.changedServer:
					var context = {"workspace": si.serverWorkspace};
					r = si.adaptor.getTiddler(si.title,context,si,getTiddlerCallback);
					break;
				case sl.notFound:
				case sl.changedLocally:
				case sl.changedBoth:
					r = si.adaptor.putTiddler(si.tiddler,null,si,putTiddlerCallback);
					break;
				default:
					break;
				}
				if(!r)
					displayMessage(errorMsg + r);
			} catch(ex) {
				if(ex.name == "TypeError")
					displayMessage("sync operation unsupported: " + ex.message);
				else
					displayMessage(errorMsg + ex.message);
			}
		}
	}
	return false;
};

//--
//-- Manager UI for groups of tiddlers
//--

config.macros.plugins.handler = function(place,macroName,params,wikifier,paramString)
{
	var wizard = new Wizard();
	wizard.createWizard(place,this.wizardTitle);
	wizard.addStep(this.step1Title,this.step1Html);
	var markList = wizard.getElement("markList");
	var listWrapper = document.createElement("div");
	markList.parentNode.insertBefore(listWrapper,markList);
	listWrapper.setAttribute("refresh","macro");
	listWrapper.setAttribute("macroName","plugins");
	listWrapper.setAttribute("params",paramString);
	this.refresh(listWrapper,paramString);
};

config.macros.plugins.refresh = function(listWrapper,params)
{
	var me = config.macros.plugins;
	var wizard = new Wizard(listWrapper);
	var selectedRows = [];
	ListView.forEachSelector(listWrapper,function(e,rowName) {
			if(e.checked)
				selectedRows.push(e.getAttribute("rowName"));
		});
	removeChildren(listWrapper);
	params = params.parseParams("anon");
	var plugins = installedPlugins.slice(0);
	var t,tiddler,p;
	var configTiddlers = store.getTaggedTiddlers("systemConfig");
	for(t=0; t<configTiddlers.length; t++) {
		tiddler = configTiddlers[t];
		if(plugins.findByField("title",tiddler.title) == null) {
			p = getPluginInfo(tiddler);
			p.executed = false;
			p.log.splice(0,0,this.skippedText);
			plugins.push(p);
		}
	}
	for(t=0; t<plugins.length; t++) {
		p = plugins[t];
		p.size = p.tiddler.text ? p.tiddler.text.length : 0;
		p.forced = p.tiddler.isTagged("systemConfigForce");
		p.disabled = p.tiddler.isTagged("systemConfigDisable");
		p.Selected = selectedRows.indexOf(plugins[t].title) != -1;
	}
	if(plugins.length == 0) {
		createTiddlyElement(listWrapper,"em",null,null,this.noPluginText);
		wizard.setButtons([]);
	} else {
		var template = readOnly ? this.listViewTemplateReadOnly : this.listViewTemplate;
		var listView = ListView.create(listWrapper,plugins,template,this.onSelectCommand);
		wizard.setValue("listView",listView);
		if(!readOnly) {
			wizard.setButtons([
				{caption: me.removeLabel, tooltip: me.removePrompt, onClick: me.doRemoveTag},
				{caption: me.deleteLabel, tooltip: me.deletePrompt, onClick: me.doDelete}
			]);
		}
	}
};

config.macros.plugins.doRemoveTag = function(e)
{
	var wizard = new Wizard(this);
	var listView = wizard.getValue("listView");
	var rowNames = ListView.getSelectedRows(listView);
	if(rowNames.length == 0) {
		alert(config.messages.nothingSelected);
	} else {
		for(var t=0; t<rowNames.length; t++)
			store.setTiddlerTag(rowNames[t],false,"systemConfig");
	}
};

config.macros.plugins.doDelete = function(e)
{
	var wizard = new Wizard(this);
	var listView = wizard.getValue("listView");
	var rowNames = ListView.getSelectedRows(listView);
	if(rowNames.length == 0) {
		alert(config.messages.nothingSelected);
	} else {
		if(confirm(config.macros.plugins.confirmDeleteText.format([rowNames.join(", ")]))) {
			for(var t=0; t<rowNames.length; t++) {
				store.removeTiddler(rowNames[t]);
				story.closeTiddler(rowNames[t],true);
			}
		}
	}
};

//--
//-- Message area
//--

function getMessageDiv()
{
	var msgArea = document.getElementById("messageArea");
	if(!msgArea)
		return null;
	if(!msgArea.hasChildNodes())
		createTiddlyButton(createTiddlyElement(msgArea,"div",null,"messageToolbar"),
			config.messages.messageClose.text,
			config.messages.messageClose.tooltip,
			clearMessage);
	msgArea.style.display = "block";
	return createTiddlyElement(msgArea,"div");
}

function displayMessage(text,linkText)
{
	var e = getMessageDiv();
	if(!e) {
		alert(text);
		return;
	}
	if(linkText) {
		var link = createTiddlyElement(e,"a",null,null,text);
		link.href = linkText;
		link.target = "_blank";
	} else {
		e.appendChild(document.createTextNode(text));
	}
}

function clearMessage()
{
	var msgArea = document.getElementById("messageArea");
	if(msgArea) {
		removeChildren(msgArea);
		msgArea.style.display = "none";
	}
	return false;
}

//--
//-- Refresh mechanism
//--

config.notifyTiddlers = [
	{name: "SystemSettings", notify: onSystemSettingsChange},
	{name: "StyleSheetLayout", notify: refreshStyles},
	{name: "StyleSheetColors", notify: refreshStyles},
	{name: "StyleSheet", notify: refreshStyles},
	{name: "StyleSheetPrint", notify: refreshStyles},
	{name: "PageTemplate", notify: refreshPageTemplate},
	{name: "SiteTitle", notify: refreshPageTitle},
	{name: "SiteSubtitle", notify: refreshPageTitle},
	{name: "WindowTitle", notify: refreshPageTitle},
	{name: "ColorPalette", notify: refreshColorPalette},
	{name: null, notify: refreshDisplay}
];

config.refreshers = {
	link: function(e,changeList)
		{
		var title = e.getAttribute("tiddlyLink");
		refreshTiddlyLink(e,title);
		return true;
		},

	tiddler: function(e,changeList)
		{
		var title = e.getAttribute("tiddler");
		var template = e.getAttribute("template");
		if(changeList && (changeList.indexOf && changeList.indexOf(title) != -1) && !story.isDirty(title))
			story.refreshTiddler(title,template,true);
		else
			refreshElements(e,changeList);
		return true;
		},

	content: function(e,changeList)
		{
		var title = e.getAttribute("tiddler");
		var force = e.getAttribute("force");
		var args = e.getAttribute("args");
		if(force != null || changeList == null || (changeList.indexOf && changeList.indexOf(title) != -1)) {
			removeChildren(e);
			config.macros.tiddler.transclude(e,title,args);
			return true;
		} else
			return false;
		},

	macro: function(e,changeList)
		{
		var macro = e.getAttribute("macroName");
		var params = e.getAttribute("params");
		if(macro)
			macro = config.macros[macro];
		if(macro && macro.refresh)
			macro.refresh(e,params);
		return true;
		}
};

config.refresherData = {
	styleSheet: "StyleSheet",
	defaultStyleSheet: "StyleSheet",
	pageTemplate: "PageTemplate",
	defaultPageTemplate: "PageTemplate",
	colorPalette: "ColorPalette",
	defaultColorPalette: "ColorPalette"
};

function refreshElements(root,changeList)
{
	var nodes = root.childNodes;
	for(var c=0; c<nodes.length; c++) {
		var e = nodes[c], type = null;
		if(e.getAttribute && (e.tagName ? e.tagName != "IFRAME" : true))
			type = e.getAttribute("refresh");
		var refresher = config.refreshers[type];
		var refreshed = false;
		if(refresher != undefined)
			refreshed = refresher(e,changeList);
		if(e.hasChildNodes() && !refreshed)
			refreshElements(e,changeList);
	}
}

function applyHtmlMacros(root,tiddler)
{
	var e = root.firstChild;
	while(e) {
		var nextChild = e.nextSibling;
		if(e.getAttribute) {
			var macro = e.getAttribute("macro");
			if(macro) {
				e.removeAttribute("macro");
				var params = "";
				var p = macro.indexOf(" ");
				if(p != -1) {
					params = macro.substr(p+1);
					macro = macro.substr(0,p);
				}
				invokeMacro(e,macro,params,null,tiddler);
			}
		}
		if(e.hasChildNodes())
			applyHtmlMacros(e,tiddler);
		e = nextChild;
	}
}

function refreshPageTemplate(title)
{
	var stash = jQuery("<div/>").appendTo("body").hide()[0];
	var display = story.getContainer();
	var nodes,t;
	if(display) {
		nodes = display.childNodes;
		for(t=nodes.length-1; t>=0; t--)
			stash.appendChild(nodes[t]);
	}
	var wrapper = document.getElementById("contentWrapper");

	var isAvailable = function(title) {
		var s = title ? title.indexOf(config.textPrimitives.sectionSeparator) : -1;
		if(s!=-1)
			title = title.substr(0,s);
		return store.tiddlerExists(title) || store.isShadowTiddler(title);
	};
	if(!title || !isAvailable(title))
		title = config.refresherData.pageTemplate;
	if(!isAvailable(title))
		title = config.refresherData.defaultPageTemplate; //# this one is always avaialable
	wrapper.innerHTML = store.getRecursiveTiddlerText(title,null,10);
	applyHtmlMacros(wrapper);
	refreshElements(wrapper);
	display = story.getContainer();
	removeChildren(display);
	if(!display)
		display = createTiddlyElement(wrapper,"div",story.containerId());
	nodes = stash.childNodes;
	for(t=nodes.length-1; t>=0; t--)
		display.appendChild(nodes[t]);
	removeNode(stash);
}

function refreshDisplay(hint)
{
	if(typeof hint == "string")
		hint = [hint];
	var e = document.getElementById("contentWrapper");
	refreshElements(e,hint);
	if(backstage.isPanelVisible()) {
		e = document.getElementById("backstage");
		refreshElements(e,hint);
	}
}

function refreshPageTitle()
{
	document.title = getPageTitle();
}

function getPageTitle()
{
	return wikifyPlain("WindowTitle");
}

function refreshStyles(title,doc)
{
	setStylesheet(title == null ? "" : store.getRecursiveTiddlerText(title,"",10),title,doc || document);
}

function refreshColorPalette(title)
{
	if(!startingUp)
		refreshAll();
}

function refreshAll()
{
	refreshPageTemplate();
	refreshDisplay();
	refreshStyles("StyleSheetLayout");
	refreshStyles("StyleSheetColors");
	refreshStyles(config.refresherData.styleSheet);
	refreshStyles("StyleSheetPrint");
}

//--
//-- Option handling
//--

config.optionHandlers = {
	'txt': {
		get: function(name) {return encodeCookie(config.options[name].toString());},
		set: function(name,value) {config.options[name] = decodeCookie(value);}
	},
	'chk': {
		get: function(name) {return config.options[name] ? 'true' : 'false';},
		set: function(name,value) {config.options[name] = value == 'true';}
	}
};

function setOption(name,value)
{
	var optType = name.substr(0,3);
	if(config.optionHandlers[optType] && config.optionHandlers[optType].set)
		config.optionHandlers[optType].set(name,value);
}

// Gets the value of an option as a string. Most code should just read from config.options.* directly
function getOption(name)
{
	var optType = name.substr(0,3);
	return config.optionHandlers[optType] && config.optionHandlers[optType].get ? config.optionHandlers[optType].get(name) : null;
}

function loadOptions()
{
	if(safeMode)
		return;
	loadCookies();
	loadSystemSettings();
}
// @Deprecated; retained for backwards compatibility
var loadOptionsCookie = loadOptions;

function getCookies()
{
	var cookieList = document.cookie.split(';');
	var cookies = {};
	for(var i=0; i<cookieList.length; i++) {
		var p = cookieList[i].indexOf('=');
		if(p != -1) {
			var name = cookieList[i].substr(0,p).trim();
			var value = cookieList[i].substr(p+1).trim();
			cookies[name] = value;
		}
	}
	return cookies;
}

function loadCookies()
{
	var cookies = getCookies();
	if(cookies['TiddlyWiki']) {
		cookies = cookies['TiddlyWiki'].decodeHashMap();
	}
	for(var i in cookies) {
		if(config.optionsSource[i] != 'setting') {
			setOption(i,cookies[i]);
		}
	}
}

function loadSystemSettings()
{
	var settings = store.calcAllSlices('SystemSettings');
	config.optionsSource = {};
	for(var key in settings) {
		setOption(key,settings[key]);
		config.optionsSource[key] = 'setting';
	}
}

function onSystemSettingsChange()
{
	if(!startingUp) {
		loadSystemSettings();
	}
}

function saveOption(name)
{
	if(safeMode)
		return;
	if(name.match(/[()\s]/g, '_')) {
		alert(config.messages.invalidCookie.format([name]));
		return;
	}
	saveCookie(name);
	if(config.optionsSource[name] == 'setting') {
		saveSystemSetting(name,true);
	}
}
// @Deprecated; retained for backwards compatibility
var saveOptionCookie = saveOption;

function removeCookie(name)
{
	document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 UTC; path=/;';
}

function saveCookie(name)
{
	var cookies = {};
	for(var key in config.options) {
		var value = getOption(key);
		value = value == null ? 'false' : value;
		cookies[key] = value;
	}
	document.cookie = 'TiddlyWiki=' + String.encodeHashMap(cookies) + '; expires=Fri, 1 Jan 2038 12:00:00 UTC; path=/';
	cookies = getCookies();
	for(var c in cookies) {
		var optType = c.substr(0,3);
		if(config.optionHandlers[optType])
			removeCookie(c);
	}
}

function saveSystemSetting(name,saveFile)
{
	var title = 'SystemSettings';
	var slice = store.getTiddlerSlice(title,name);
	if(readOnly || slice === getOption(name)) {
		return; //# don't save if read-only or the option hasn't changed
	}
	var slices = store.calcAllSlices(title);
	var key;
	for(key in config.optionsSource) {
		var value = getOption(key) || '';
		if(slices[key] !== value) {
			slices[key] = value;
		}
	}
	var text = [];
	for(key in slices) {
		text.push('%0: %1'.format([key,slices[key]]));
	}
	text = text.sort().join('\n');
	var storeWasDirty = store.isDirty();
	var tiddler = store.getTiddler(title);
	if(tiddler) {
		tiddler.text = text;
		tiddler = store.saveTiddler(tiddler);
	} else {
		tiddler = store.saveTiddler(title,title,text,'System',new Date(),['excludeLists'],config.defaultCustomFields);
	}
	if(saveFile) {
		if(storeWasDirty == false && story.areAnyDirty() == false) {
			saveChanges(null,[tiddler]);
		} else {
			autoSaveChanges(null,[tiddler]);
		
		}
    }
}

function encodeCookie(s)
{
	return escape(convertUnicodeToHtmlEntities(s));
}

function decodeCookie(s)
{
	s = unescape(s);
	var re = /&#[0-9]{1,5};/g;
	return s.replace(re,function($0) {return String.fromCharCode(eval($0.replace(/[&#;]/g,'')));});
}

config.macros.option.genericCreate = function(place,type,opt,className,desc)
{
	var typeInfo = config.macros.option.types[type];
	var c = document.createElement(typeInfo.elementType);
	if(typeInfo.typeValue)
		c.setAttribute('type',typeInfo.typeValue);
	c[typeInfo.eventName] = typeInfo.onChange;
	c.setAttribute('option',opt);
	c.className = className || typeInfo.className;
	if(config.optionsDesc[opt])
		c.setAttribute('title',config.optionsDesc[opt]);
	place.appendChild(c);
	if(desc != 'no')
		createTiddlyText(place,config.optionsDesc[opt] || opt);
	c[typeInfo.valueField] = config.options[opt];
	return c;
};

config.macros.option.genericOnChange = function(e)
{
	var opt = this.getAttribute('option');
	if(opt) {
		var optType = opt.substr(0,3);
		var handler = config.macros.option.types[optType];
		if(handler.elementType && handler.valueField)
			config.macros.option.propagateOption(opt,handler.valueField,this[handler.valueField],handler.elementType,this);
	}
	return true;
};

config.macros.option.types = {
	'txt': {
		elementType: 'input',
		valueField: 'value',
		eventName: 'onchange',
		className: 'txtOptionInput',
		create: config.macros.option.genericCreate,
		onChange: config.macros.option.genericOnChange
	},
	'chk': {
		elementType: 'input',
		valueField: 'checked',
		eventName: 'onclick',
		className: 'chkOptionInput',
		typeValue: 'checkbox',
		create: config.macros.option.genericCreate,
		onChange: config.macros.option.genericOnChange
	}
};

config.macros.option.propagateOption = function(opt,valueField,value,elementType,elem)
{
	config.options[opt] = value;
	saveOption(opt);
	var nodes = document.getElementsByTagName(elementType);
	for(var t=0; t<nodes.length; t++) {
		var optNode = nodes[t].getAttribute('option');
		if(opt == optNode && nodes[t]!=elem)
			nodes[t][valueField] = value;
	}
};

config.macros.option.handler = function(place,macroName,params,wikifier,paramString)
{
	params = paramString.parseParams('anon',null,true,false,false);
	var opt = (params[1] && params[1].name == 'anon') ? params[1].value : getParam(params,'name',null);
	var className = (params[2] && params[2].name == 'anon') ? params[2].value : getParam(params,'class',null);
	var desc = getParam(params,'desc','no');
	var type = opt.substr(0,3);
	var h = config.macros.option.types[type];
	if(h && h.create)
		h.create(place,type,opt,className,desc);
};

config.macros.options.handler = function(place,macroName,params,wikifier,paramString)
{
	params = paramString.parseParams('anon',null,true,false,false);
	var showUnknown = getParam(params,'showUnknown','no');
	var wizard = new Wizard();
	wizard.createWizard(place,this.wizardTitle);
	wizard.addStep(this.step1Title,this.step1Html);
	var markList = wizard.getElement('markList');
	var chkUnknown = wizard.getElement('chkUnknown');
	chkUnknown.checked = showUnknown == 'yes';
	chkUnknown.onchange = this.onChangeUnknown;
	var listWrapper = document.createElement('div');
	markList.parentNode.insertBefore(listWrapper,markList);
	wizard.setValue('listWrapper',listWrapper);
	this.refreshOptions(listWrapper,showUnknown == 'yes');
};

config.macros.options.refreshOptions = function(listWrapper,showUnknown)
{
	var opts = [];
	for(var n in config.options) {
		var opt = {};
		opt.option = '';
		opt.name = n;
		opt.lowlight = !config.optionsDesc[n];
		opt.description = opt.lowlight ? this.unknownDescription : config.optionsDesc[n];
		if(!opt.lowlight || showUnknown)
			opts.push(opt);
	}
	opts.sort(function(a,b) {return a.name.substr(3) < b.name.substr(3) ? -1 : (a.name.substr(3) == b.name.substr(3) ? 0 : +1);});
	var listview = ListView.create(listWrapper,opts,this.listViewTemplate);
	for(n=0; n<opts.length; n++) {
		var type = opts[n].name.substr(0,3);
		var h = config.macros.option.types[type];
		if(h && h.create) {
			h.create(opts[n].colElements['option'],type,opts[n].name,null,'no');
		}
	}
};

config.macros.options.onChangeUnknown = function(e)
{
	var wizard = new Wizard(this);
	var listWrapper = wizard.getValue('listWrapper');
	removeChildren(listWrapper);
	config.macros.options.refreshOptions(listWrapper,this.checked);
	return false;
};

//--
//-- Saving
//--

var saveUsingSafari = false;

var startSaveArea = '<div id="' + 'storeArea">'; // Split up into two so that indexOf() of this source doesn't find it
var endSaveArea = '</d' + 'iv>';

// If there are unsaved changes, force the user to confirm before exitting
function confirmExit()
{
	hadConfirmExit = true;
	if((store && store.isDirty && store.isDirty()) || (story && story.areAnyDirty && story.areAnyDirty()))
		return config.messages.confirmExit;
}

// Give the user a chance to save changes before exitting
function checkUnsavedChanges()
{
	if(store && store.isDirty && store.isDirty() && window.hadConfirmExit === false) {
		if(confirm(config.messages.unsavedChangesWarning))
			saveChanges();
	}
}

function updateLanguageAttribute(s)
{
	if(config.locale) {
		var mRE = /(<html(?:.*?)?)(?: xml:lang\="([a-z]+)")?(?: lang\="([a-z]+)")?>/;
		var m = mRE.exec(s);
		if(m) {
			var t = m[1];
			if(m[2])
				t += ' xml:lang="' + config.locale + '"';
			if(m[3])
				t += ' lang="' + config.locale + '"';
			t += ">";
			s = s.substr(0,m.index) + t + s.substr(m.index+m[0].length);
		}
	}
	return s;
}

function updateMarkupBlock(s,blockName,tiddlerName)
{
	return s.replaceChunk(
			"<!--%0-START-->".format([blockName]),
			"<!--%0-END-->".format([blockName]),
			"\n" + convertUnicodeToFileFormat(store.getRecursiveTiddlerText(tiddlerName,"")) + "\n");
}

function updateOriginal(original,posDiv,localPath)
{
	if(!posDiv)
		posDiv = locateStoreArea(original);
	if(!posDiv) {
		alert(config.messages.invalidFileError.format([localPath]));
		return null;
	}
	var revised = original.substr(0,posDiv[0] + startSaveArea.length) + "\n" +
				convertUnicodeToFileFormat(store.allTiddlersAsHtml()) + "\n" +
				original.substr(posDiv[1]);
	var newSiteTitle = convertUnicodeToFileFormat(getPageTitle()).htmlEncode();
	revised = revised.replaceChunk("<title"+">","</title"+">"," " + newSiteTitle + " ");
	revised = updateLanguageAttribute(revised);
	revised = updateMarkupBlock(revised,"PRE-HEAD","MarkupPreHead");
	revised = updateMarkupBlock(revised,"POST-HEAD","MarkupPostHead");
	revised = updateMarkupBlock(revised,"PRE-BODY","MarkupPreBody");
	revised = updateMarkupBlock(revised,"POST-SCRIPT","MarkupPostBody");
	return revised;
}

function locateStoreArea(original)
{
	// Locate the storeArea div's
	var posOpeningDiv = original.indexOf(startSaveArea);
	var limitClosingDiv = original.indexOf("<"+"!--POST-STOREAREA--"+">");
	if(limitClosingDiv == -1)
		limitClosingDiv = original.indexOf("<"+"!--POST-BODY-START--"+">");
	var posClosingDiv = original.lastIndexOf(endSaveArea,limitClosingDiv == -1 ? original.length : limitClosingDiv);
	return (posOpeningDiv != -1 && posClosingDiv != -1) ? [posOpeningDiv,posClosingDiv] : null;
}

function autoSaveChanges(onlyIfDirty,tiddlers)
{
	if(config.options.chkAutoSave)
		saveChanges(onlyIfDirty,tiddlers);
}

function loadOriginal(localPath)
{
	return loadFile(localPath);
}

// Save this tiddlywiki with the pending changes
function saveChanges(onlyIfDirty,tiddlers)
{
	if(onlyIfDirty && !store.isDirty())
		return;
	clearMessage();
	var t0 = new Date();
	var msg = config.messages;
	var originalPath = document.location.toString();
	if(originalPath.substr(0,5) != "file:") {
		alert(msg.notFileUrlError);
		if(store.tiddlerExists(msg.saveInstructions))
			story.displayTiddler(null,msg.saveInstructions);
		return;
	}
	var localPath = getLocalPath(originalPath);
	var original = loadOriginal(localPath);
	if(original == null) {
		alert(msg.cantSaveError);
		if(store.tiddlerExists(msg.saveInstructions))
			story.displayTiddler(null,msg.saveInstructions);
		return;
	}
	var posDiv = locateStoreArea(original);
	if(!posDiv) {
		alert(msg.invalidFileError.format([localPath]));
		return;
	}
	saveMain(localPath,original,posDiv);
	if(config.options.chkSaveBackups)
		saveBackup(localPath,original);
	if(config.options.chkSaveEmptyTemplate)
		saveEmpty(localPath,original,posDiv);
	if(config.options.chkGenerateAnRssFeed && saveRss instanceof Function)
		saveRss(localPath);
	if(config.options.chkDisplayInstrumentation)
		displayMessage("saveChanges " + (new Date()-t0) + " ms");
}

function saveMain(localPath,original,posDiv)
{
	var save;
	try {
		var revised = updateOriginal(original,posDiv,localPath);
		save = saveFile(localPath,revised);
	} catch (ex) {
		showException(ex);
	}
	if(save) {
		displayMessage(config.messages.mainSaved,"file://" + localPath);
		store.setDirty(false);
	} else {
		alert(config.messages.mainFailed);
	}
}

function saveBackup(localPath,original)
{
	var backupPath = getBackupPath(localPath);
	var backup = copyFile(backupPath,localPath);
	if(!backup)
		backup = saveFile(backupPath,original);
	if(backup)
		displayMessage(config.messages.backupSaved,"file://" + backupPath);
	else
		alert(config.messages.backupFailed);
}

function saveEmpty(localPath,original,posDiv)
{
	var emptyPath,p;
	if((p = localPath.lastIndexOf("/")) != -1)
		emptyPath = localPath.substr(0,p) + "/";
	else if((p = localPath.lastIndexOf("\\")) != -1)
		emptyPath = localPath.substr(0,p) + "\\";
	else
		emptyPath = localPath + ".";
	emptyPath += "empty.html";
	var empty = original.substr(0,posDiv[0] + startSaveArea.length) + original.substr(posDiv[1]);
	var emptySave = saveFile(emptyPath,empty);
	if(emptySave)
		displayMessage(config.messages.emptySaved,"file://" + emptyPath);
	else
		alert(config.messages.emptyFailed);
}

function getLocalPath(origPath)
{
	var originalPath = convertUriToUTF8(origPath,config.options.txtFileSystemCharSet);
	// Remove any location or query part of the URL
	var argPos = originalPath.indexOf("?");
	if(argPos != -1)
		originalPath = originalPath.substr(0,argPos);
	var hashPos = originalPath.indexOf("#");
	if(hashPos != -1)
		originalPath = originalPath.substr(0,hashPos);
	// Convert file://localhost/ to file:///
	if(originalPath.indexOf("file://localhost/") == 0)
		originalPath = "file://" + originalPath.substr(16);
	// Convert to a native file format
	var localPath;
	if(originalPath.charAt(9) == ":") // pc local file
		localPath = unescape(originalPath.substr(8)).replace(new RegExp("/","g"),"\\");
	else if(originalPath.indexOf("file://///") == 0) // FireFox pc network file
		localPath = "\\\\" + unescape(originalPath.substr(10)).replace(new RegExp("/","g"),"\\");
	else if(originalPath.indexOf("file:///") == 0) // mac/unix local file
		localPath = unescape(originalPath.substr(7));
	else if(originalPath.indexOf("file:/") == 0) // mac/unix local file
		localPath = unescape(originalPath.substr(5));
	else // pc network file
		localPath = "\\\\" + unescape(originalPath.substr(7)).replace(new RegExp("/","g"),"\\");
	return localPath;
}

function getBackupPath(localPath,title,extension)
{
	var slash = "\\";
	var dirPathPos = localPath.lastIndexOf("\\");
	if(dirPathPos == -1) {
		dirPathPos = localPath.lastIndexOf("/");
		slash = "/";
	}
	var backupFolder = config.options.txtBackupFolder;
	if(!backupFolder || backupFolder == "")
		backupFolder = ".";
	var backupPath = localPath.substr(0,dirPathPos) + slash + backupFolder + localPath.substr(dirPathPos);
	backupPath = backupPath.substr(0,backupPath.lastIndexOf(".")) + ".";
	if(title)
		backupPath += title.replace(/[\\\/\*\?\":<> ]/g,"_") + ".";
	backupPath += (new Date()).convertToYYYYMMDDHHMMSSMMM() + "." + (extension || "html");
	return backupPath;
}

//--
//-- RSS Saving
//--

function saveRss(localPath)
{
	var rssPath = localPath.substr(0,localPath.lastIndexOf(".")) + ".xml";
	if(saveFile(rssPath,convertUnicodeToFileFormat(generateRss())))
		displayMessage(config.messages.rssSaved,"file://" + rssPath);
	else
		alert(config.messages.rssFailed);
}

tiddlerToRssItem = function(tiddler,uri)
{
	var s = "<title" + ">" + tiddler.title.htmlEncode() + "</title" + ">\n";
	s += "<description>" + wikifyStatic(tiddler.text,null,tiddler).htmlEncode() + "</description>\n";
	for(var i=0; i<tiddler.tags.length; i++)
		s += "<category>" + tiddler.tags[i] + "</category>\n";
	s += "<link>" + uri + "#" + encodeURIComponent(String.encodeTiddlyLink(tiddler.title)) + "</link>\n";
	s +="<pubDate>" + tiddler.modified.toGMTString() + "</pubDate>\n";
	return s;
};

function generateRss()
{
	var s = [];
	var d = new Date();
	var u = store.getTiddlerText("SiteUrl");
	// Assemble the header
	s.push("<" + "?xml version=\"1.0\"?" + ">");
	s.push("<rss version=\"2.0\">");
	s.push("<channel>");
	s.push("<title" + ">" + wikifyPlain("SiteTitle").htmlEncode() + "</title" + ">");
	if(u)
		s.push("<link>" + u.htmlEncode() + "</link>");
	s.push("<description>" + wikifyPlain("SiteSubtitle").htmlEncode() + "</description>");
	s.push("<language>" + config.locale + "</language>");
	s.push("<copyright>Copyright " + d.getFullYear() + " " + config.options.txtUserName.htmlEncode() + "</copyright>");
	s.push("<pubDate>" + d.toGMTString() + "</pubDate>");
	s.push("<lastBuildDate>" + d.toGMTString() + "</lastBuildDate>");
	s.push("<docs>http://blogs.law.harvard.edu/tech/rss</docs>");
	s.push("<generator>TiddlyWiki " + formatVersion() + "</generator>");
	// The body
	var tiddlers = store.getTiddlers("modified","excludeLists");
	var n = config.numRssItems > tiddlers.length ? 0 : tiddlers.length-config.numRssItems;
	for(var i=tiddlers.length-1; i>=n; i--) {
		s.push("<item>\n" + tiddlerToRssItem(tiddlers[i],u) + "\n</item>");
	}
	// And footer
	s.push("</channel>");
	s.push("</rss>");
	// Save it all
	return s.join("\n");
}

//--
//-- Filesystem code
//--

function convertUTF8ToUnicode(u)
{
	return config.browser.isOpera || !window.netscape ? manualConvertUTF8ToUnicode(u) : mozConvertUTF8ToUnicode(u);
}

function manualConvertUTF8ToUnicode(utf)
{
	var uni = utf;
	var src = 0;
	var dst = 0;
	var b1, b2, b3;
	var c;
	while(src < utf.length) {
		b1 = utf.charCodeAt(src++);
		if(b1 < 0x80) {
			dst++;
		} else if(b1 < 0xE0) {
			b2 = utf.charCodeAt(src++);
			c = String.fromCharCode(((b1 & 0x1F) << 6) | (b2 & 0x3F));
			uni = uni.substring(0,dst++).concat(c,utf.substr(src));
		} else {
			b2 = utf.charCodeAt(src++);
			b3 = utf.charCodeAt(src++);
			c = String.fromCharCode(((b1 & 0xF) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F));
			uni = uni.substring(0,dst++).concat(c,utf.substr(src));
		}
	}
	return uni;
}

function mozConvertUTF8ToUnicode(u)
{
	try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
		converter.charset = "UTF-8";
	} catch(ex) {
		return manualConvertUTF8ToUnicode(u);
	} // fallback
	var s = converter.ConvertToUnicode(u);
	var fin = converter.Finish();
	return fin.length > 0 ? s+fin : s;
}

function convertUnicodeToFileFormat(s)
{
	return config.browser.isOpera || !window.netscape ? (config.browser.isIE ? convertUnicodeToHtmlEntities(s) : s) : mozConvertUnicodeToUTF8(s);
}

function convertUnicodeToHtmlEntities(s)
{
	var re = /[^\u0000-\u007F]/g;
	return s.replace(re,function($0) {return "&#" + $0.charCodeAt(0).toString() + ";";});
}

function convertUnicodeToUTF8(s)
{
// return convertUnicodeToFileFormat to allow plugin migration
	return convertUnicodeToFileFormat(s);
}

function manualConvertUnicodeToUTF8(s)
{
	return unescape(encodeURIComponent(s));
}

function mozConvertUnicodeToUTF8(s)
{
	try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
		converter.charset = "UTF-8";
	} catch(ex) {
		return manualConvertUnicodeToUTF8(s);
	} // fallback
	var u = converter.ConvertFromUnicode(s);
	var fin = converter.Finish();
	return fin.length > 0 ? u + fin : u;
}

function convertUriToUTF8(uri,charSet)
{
	if(window.netscape == undefined || charSet == undefined || charSet == "")
		return uri;
	try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
		var converter = Components.classes["@mozilla.org/intl/utf8converterservice;1"].getService(Components.interfaces.nsIUTF8ConverterService);
	} catch(ex) {
		return uri;
	}
	return converter.convertURISpecToUTF8(uri,charSet);
}

function copyFile(dest,source)
{
	return config.browser.isIE ? ieCopyFile(dest,source) : false;
}

function saveFile(fileUrl,content)
{
	var r = mozillaSaveFile(fileUrl,content);
	if(!r)
		r = ieSaveFile(fileUrl,content);
	if(!r)
		r = javaSaveFile(fileUrl,content);
	return r;
}

function loadFile(fileUrl)
{
	var r = mozillaLoadFile(fileUrl);
	if((r == null) || (r == false))
		r = ieLoadFile(fileUrl);
	if((r == null) || (r == false))
		r = javaLoadFile(fileUrl);
	return r;
}

function ieCreatePath(path)
{
	try {
		var fso = new ActiveXObject("Scripting.FileSystemObject");
	} catch(ex) {
		return null;
	}

	var pos = path.lastIndexOf("\\");
	if(pos==-1)
		pos = path.lastIndexOf("/");
	if(pos!=-1)
		path = path.substring(0,pos+1);

	var scan = [path];
	var parent = fso.GetParentFolderName(path);
	while(parent && !fso.FolderExists(parent)) {
		scan.push(parent);
		parent = fso.GetParentFolderName(parent);
	}

	for(i=scan.length-1;i>=0;i--) {
		if(!fso.FolderExists(scan[i])) {
			fso.CreateFolder(scan[i]);
		}
	}
	return true;
}

// Returns null if it can't do it, false if there's an error, true if it saved OK
function ieSaveFile(filePath,content)
{
	ieCreatePath(filePath);
	try {
		var fso = new ActiveXObject("Scripting.FileSystemObject");
	} catch(ex) {
		return null;
	}
	var file = fso.OpenTextFile(filePath,2,-1,0);
	file.Write(content);
	file.Close();
	return true;
}

// Returns null if it can't do it, false if there's an error, or a string of the content if successful
function ieLoadFile(filePath)
{
	try {
		var fso = new ActiveXObject("Scripting.FileSystemObject");
		var file = fso.OpenTextFile(filePath,1);
		var content = file.ReadAll();
		file.Close();
	} catch(ex) {
		return null;
	}
	return content;
}

function ieCopyFile(dest,source)
{
	ieCreatePath(dest);
	try {
		var fso = new ActiveXObject("Scripting.FileSystemObject");
		fso.GetFile(source).Copy(dest);
	} catch(ex) {
		return false;
	}
	return true;
}

// Returns null if it can't do it, false if there's an error, true if it saved OK
function mozillaSaveFile(filePath,content)
{
	if(window.Components) {
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
			file.initWithPath(filePath);
			if(!file.exists())
				file.create(0,0664);
			var out = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
			out.init(file,0x20|0x02,00004,null);
			out.write(content,content.length);
			out.flush();
			out.close();
			return true;
		} catch(ex) {
			return false;
		}
	}
	return null;
}

// Returns null if it can't do it, false if there's an error, or a string of the content if successful
function mozillaLoadFile(filePath)
{
	if(window.Components) {
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
			var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
			file.initWithPath(filePath);
			if(!file.exists())
				return null;
			var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
			inputStream.init(file,0x01,00004,null);
			var sInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
			sInputStream.init(inputStream);
			var contents = sInputStream.read(sInputStream.available());
			sInputStream.close();
			inputStream.close();
			return contents;
		} catch(ex) {
			return false;
		}
	}
	return null;
}

function javaUrlToFilename(url)
{
	var f = "//localhost";
	if(url.indexOf(f) == 0)
		return url.substring(f.length);
	var i = url.indexOf(":");
	return i > 0 ? url.substring(i-1) : url;
}

function javaSaveFile(filePath,content)
{
	try {
		if(document.applets["TiddlySaver"])
			return document.applets["TiddlySaver"].saveFile(javaUrlToFilename(filePath),"UTF-8",content);
	} catch(ex) {
	}
	try {
		var s = new java.io.PrintStream(new java.io.FileOutputStream(javaUrlToFilename(filePath)));
		s.print(content);
		s.close();
	} catch(ex) {
		return null;
	}
	return true;
}

function javaLoadFile(filePath)
{
	try {
		if(document.applets["TiddlySaver"])
			return String(document.applets["TiddlySaver"].loadFile(javaUrlToFilename(filePath),"UTF-8"));
	} catch(ex) {
	}
	var content = [];
	try {
		var r = new java.io.BufferedReader(new java.io.FileReader(javaUrlToFilename(filePath)));
		var line;
		while((line = r.readLine()) != null)
			content.push(new String(line));
		r.close();
	} catch(ex) {
		return null;
	}
	return content.join("\n");
}

//--
//-- Server adaptor base class
//--

function AdaptorBase()
{
	this.host = null;
	this.store = null;
	return this;
}

AdaptorBase.prototype.close = function()
{
	return true;
};

AdaptorBase.prototype.fullHostName = function(host)
{
	if(!host)
		return '';
	host = host.trim();
	if(!host.match(/:\/\//))
		host = 'http://' + host;
	if(host.substr(host.length-1) == '/')
		host = host.substr(0,host.length-1);
	return host;
};

AdaptorBase.minHostName = function(host)
{
	return host;
};

AdaptorBase.prototype.setContext = function(context,userParams,callback)
{
	if(!context) context = {};
	context.userParams = userParams;
	if(callback) context.callback = callback;
	context.adaptor = this;
	if(!context.host)
		context.host = this.host;
	context.host = this.fullHostName(context.host);
	if(!context.workspace)
		context.workspace = this.workspace;
	return context;
};

// Open the specified host
AdaptorBase.prototype.openHost = function(host,context,userParams,callback)
{
	this.host = host;
	context = this.setContext(context,userParams,callback);
	context.status = true;
	if(callback)
		window.setTimeout(function() {context.callback(context,userParams);},10);
	return true;
};

// Open the specified workspace
AdaptorBase.prototype.openWorkspace = function(workspace,context,userParams,callback)
{
	this.workspace = workspace;
	context = this.setContext(context,userParams,callback);
	context.status = true;
	if(callback)
		window.setTimeout(function() {callback(context,userParams);},10);
	return true;
};

//--
//-- Server adaptor for talking to static TiddlyWiki files
//--

function FileAdaptor()
{
}

FileAdaptor.prototype = new AdaptorBase();

FileAdaptor.serverType = 'file';
FileAdaptor.serverLabel = 'TiddlyWiki';

FileAdaptor.loadTiddlyWikiCallback = function(status,context,responseText,url,xhr)
{
	context.status = status;
	if(!status) {
		context.statusText = "Error reading file";
	} else {
		context.adaptor.store = new TiddlyWiki();
		if(!context.adaptor.store.importTiddlyWiki(responseText)) {
			context.statusText = config.messages.invalidFileError.format([url]);
			context.status = false;
		}
	}
	context.complete(context,context.userParams);
};

// Get the list of workspaces on a given server
FileAdaptor.prototype.getWorkspaceList = function(context,userParams,callback)
{
	context = this.setContext(context,userParams,callback);
	context.workspaces = [{title:"(default)"}];
	context.status = true;
	if(callback)
		window.setTimeout(function() {callback(context,userParams);},10);
	return true;
};

// Gets the list of tiddlers within a given workspace
FileAdaptor.prototype.getTiddlerList = function(context,userParams,callback,filter)
{
	context = this.setContext(context,userParams,callback);
	if(!context.filter)
		context.filter = filter;
	context.complete = FileAdaptor.getTiddlerListComplete;
	if(this.store) {
		var ret = context.complete(context,context.userParams);
	} else {
		ret = loadRemoteFile(context.host,FileAdaptor.loadTiddlyWikiCallback,context);
		if(typeof ret != "string")
			ret = true;
	}
	return ret;
};

FileAdaptor.getTiddlerListComplete = function(context,userParams)
{
	if(context.status) {
		if(context.filter) {
			context.tiddlers = context.adaptor.store.filterTiddlers(context.filter);
		} else {
			context.tiddlers = [];
			context.adaptor.store.forEachTiddler(function(title,tiddler) {context.tiddlers.push(tiddler);});
		}
		for(var i=0; i<context.tiddlers.length; i++) {
			context.tiddlers[i].fields['server.type'] = FileAdaptor.serverType;
			context.tiddlers[i].fields['server.host'] = AdaptorBase.minHostName(context.host);
			context.tiddlers[i].fields['server.page.revision'] = context.tiddlers[i].modified.convertToYYYYMMDDHHMM();
		}
		context.status = true;
	}
	if(context.callback) {
		window.setTimeout(function() {context.callback(context,userParams);},10);
	}
	return true;
};

FileAdaptor.prototype.generateTiddlerInfo = function(tiddler)
{
	var info = {};
	info.uri = tiddler.fields['server.host'] + "#" + tiddler.title;
	return info;
};

// Retrieve a tiddler from a given workspace on a given server
FileAdaptor.prototype.getTiddler = function(title,context,userParams,callback)
{
	context = this.setContext(context,userParams,callback);
	context.title = title;
	context.complete = FileAdaptor.getTiddlerComplete;
	return context.adaptor.store ?
		context.complete(context,context.userParams) :
		loadRemoteFile(context.host,FileAdaptor.loadTiddlyWikiCallback,context);
};

FileAdaptor.getTiddlerComplete = function(context,userParams)
{
	var t = context.adaptor.store.fetchTiddler(context.title);
	if(t) {
		t.fields['server.type'] = FileAdaptor.serverType;
		t.fields['server.host'] = AdaptorBase.minHostName(context.host);
		t.fields['server.page.revision'] = t.modified.convertToYYYYMMDDHHMM();
		context.tiddler = t;
		context.status = true;
	} else { //# tiddler does not exist in document
		context.status = false;
	}
	if(context.allowSynchronous) {
		context.isSynchronous = true;
		context.callback(context,userParams);
	} else {
		window.setTimeout(function() {context.callback(context,userParams);},10);
	}
	return true;
};

FileAdaptor.prototype.close = function()
{
	this.store = null;
};

config.adaptors[FileAdaptor.serverType] = FileAdaptor;

config.defaultAdaptor = FileAdaptor.serverType;

//--
//-- HTTP request code
//--

function ajaxReq(args)
{
	if(window.Components && window.netscape && window.netscape.security && document.location.protocol.indexOf("http") == -1)
		window.netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	return jQuery.ajax(args);
}

//--
//-- TiddlyWiki-specific utility functions
//--

// Returns TiddlyWiki version string
function formatVersion(v)
{
	v = v || version;
	return v.major + "." + v.minor + "." + v.revision +
		(v.alpha ? " (alpha " + v.alpha + ")" : "") +
		(v.beta ? " (beta " + v.beta + ")" : "");
}

function compareVersions(v1,v2)
{
	var a = ["major","minor","revision"];
	for(var i = 0; i<a.length; i++) {
		var x1 = v1[a[i]] || 0;
		var x2 = v2[a[i]] || 0;
		if(x1<x2)
			return 1;
		if(x1>x2)
			return -1;
	}
	x1 = v1.beta || 9999;
	x2 = v2.beta || 9999;
	if(x1<x2)
		return 1;
	return x1 > x2 ? -1 : 0;
}

function createTiddlyButton(parent,text,tooltip,action,className,id,accessKey,attribs)
{
	var btn = document.createElement("a");
	if(action) {
		btn.onclick = action;
		btn.setAttribute("href","javascript:;");
	}
	if(tooltip)
		btn.setAttribute("title",tooltip);
	if(text)
		btn.appendChild(document.createTextNode(text));
	btn.className = className || "button";
	if(id)
		btn.id = id;
	if(attribs) {
		for(var i in attribs) {
			btn.setAttribute(i,attribs[i]);
		}
	}
	if(parent)
		parent.appendChild(btn);
	if(accessKey)
		btn.setAttribute("accessKey",accessKey);
	return btn;
}

function createTiddlyLink(place,title,includeText,className,isStatic,linkedFromTiddler,noToggle)
{
	var text = includeText ? title : null;
	var i = getTiddlyLinkInfo(title,className);
	var btn = isStatic ? createExternalLink(place,store.getTiddlerText("SiteUrl",null) + "#" + title) : createTiddlyButton(place,text,i.subTitle,onClickTiddlerLink,i.classes);
	if(isStatic)
		btn.className += ' ' + className;
	btn.setAttribute("refresh","link");
	btn.setAttribute("tiddlyLink",title);
	if(noToggle)
		btn.setAttribute("noToggle","true");
	if(linkedFromTiddler) {
		var fields = linkedFromTiddler.getInheritedFields();
		if(fields)
			btn.setAttribute("tiddlyFields",fields);
	}
	return btn;
}

function refreshTiddlyLink(e,title)
{
	var i = getTiddlyLinkInfo(title,e.className);
	e.className = i.classes;
	e.title = i.subTitle;
}

function getTiddlyLinkInfo(title,currClasses)
{
	var classes = currClasses ? currClasses.split(" ") : [];
	classes.pushUnique("tiddlyLink");
	var tiddler = store.fetchTiddler(title);
	var subTitle;
	if(tiddler) {
		subTitle = tiddler.getSubtitle();
		classes.pushUnique("tiddlyLinkExisting");
		classes.remove("tiddlyLinkNonExisting");
		classes.remove("shadow");
	} else {
		classes.remove("tiddlyLinkExisting");
		classes.pushUnique("tiddlyLinkNonExisting");
		if(store.isShadowTiddler(title)) {
			subTitle = config.messages.shadowedTiddlerToolTip.format([title]);
			classes.pushUnique("shadow");
		} else {
			subTitle = config.messages.undefinedTiddlerToolTip.format([title]);
			classes.remove("shadow");
		}
	}
	if(typeof config.annotations[title]=="string")
		subTitle = config.annotations[title];
	return {classes: classes.join(" "),subTitle: subTitle};
}

function createExternalLink(place,url,label)
{
	var link = document.createElement("a");
	link.className = "externalLink";
	link.href = url;
	link.title = config.messages.externalLinkTooltip.format([url]);
	if(config.options.chkOpenInNewWindow)
		link.target = "_blank";
	place.appendChild(link);
	if(label)
		createTiddlyText(link, label);
	return link;
}

// Event handler for clicking on a tiddly link
function onClickTiddlerLink(ev)
{
	var e = ev || window.event;
	var target = resolveTarget(e);
	var link = target;
	var title = null;
	var fields = null;
	var noToggle = null;
	do {
		title = link.getAttribute("tiddlyLink");
		fields = link.getAttribute("tiddlyFields");
		noToggle = link.getAttribute("noToggle");
		link = link.parentNode;
	} while(title == null && link != null);
	if(!store.isShadowTiddler(title)) {
		var f = fields ? fields.decodeHashMap() : {};
		fields = String.encodeHashMap(merge(f,config.defaultCustomFields,true));
	}
	if(title) {
		var toggling = e.metaKey || e.ctrlKey;
		if(config.options.chkToggleLinks)
			toggling = !toggling;
		if(noToggle)
			toggling = false;
		if(store.getTiddler(title))
			fields = null;
		story.displayTiddler(target,title,null,true,null,fields,toggling);
	}
	clearMessage();
	return false;
}

// Create a button for a tag with a popup listing all the tiddlers that it tags
function createTagButton(place,tag,excludeTiddler,title,tooltip)
{
	var btn = createTiddlyButton(place,title||tag,(tooltip||config.views.wikified.tag.tooltip).format([tag]),onClickTag);
	btn.setAttribute("tag",tag);
	if(excludeTiddler)
		btn.setAttribute("tiddler",excludeTiddler);
	return btn;
}

// Event handler for clicking on a tiddler tag
function onClickTag(ev)
{
	var e = ev || window.event;
	var popup = Popup.create(this);
	addClass(popup,"taggedTiddlerList");
	var tag = this.getAttribute("tag");
	var title = this.getAttribute("tiddler");
	if(popup && tag) {
		var tagged = tag.indexOf("[")==-1 ? store.getTaggedTiddlers(tag) : store.filterTiddlers(tag);
		var sortby = this.getAttribute("sortby");
		if(sortby&&sortby.length) {
			store.sortTiddlers(tagged,sortby);
		}
		var titles = [];
		var li,r;
		for(r=0;r<tagged.length;r++) {
			if(tagged[r].title != title)
				titles.push(tagged[r].title);
		}
		var lingo = config.views.wikified.tag;
		if(titles.length > 0) {
			var openAll = createTiddlyButton(createTiddlyElement(popup,"li"),lingo.openAllText.format([tag]),lingo.openAllTooltip,onClickTagOpenAll);
			openAll.setAttribute("tag",tag);
			openAll.setAttribute("sortby",sortby);
			createTiddlyElement(createTiddlyElement(popup,"li",null,"listBreak"),"div");
			for(r=0; r<titles.length; r++) {
				createTiddlyLink(createTiddlyElement(popup,"li"),titles[r],true);
			}
		} else {
			createTiddlyElement(popup,"li",null,"disabled",lingo.popupNone.format([tag]));
		}
		createTiddlyElement(createTiddlyElement(popup,"li",null,"listBreak"),"div");
		var h = createTiddlyLink(createTiddlyElement(popup,"li"),tag,false);
		createTiddlyText(h,lingo.openTag.format([tag]));
	}
	Popup.show();
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	return false;
}

// Event handler for 'open all' on a tiddler popup
function onClickTagOpenAll(ev)
{
	var tiddlers = store.getTaggedTiddlers(this.getAttribute("tag"));
	var sortby = this.getAttribute("sortby");
	if(sortby&&sortby.length) {
		store.sortTiddlers(tiddlers,sortby);
	}
	story.displayTiddlers(this,tiddlers);
	return false;
}

function onClickError(ev)
{
	var e = ev || window.event;
	var popup = Popup.create(this);
	var lines = this.getAttribute("errorText").split("\n");
	for(var t=0; t<lines.length; t++)
		createTiddlyElement(popup,"li",null,null,lines[t]);
	Popup.show();
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
	return false;
}

function createTiddlyDropDown(place,onchange,options,defaultValue)
{
	var sel = createTiddlyElement(place,"select");
	sel.onchange = onchange;
	for(var t=0; t<options.length; t++) {
		var e = createTiddlyElement(sel,"option",null,null,options[t].caption);
		e.value = options[t].name;
		if(options[t].name == defaultValue)
			e.selected = true;
	}
	return sel;
}

function createTiddlyPopup(place,caption,tooltip,tiddler)
{
	if(tiddler.text) {
		createTiddlyLink(place,caption,true);
		var btn = createTiddlyButton(place,glyph("downArrow"),tooltip,onClickTiddlyPopup,"tiddlerPopupButton");
		btn.tiddler = tiddler;
	} else {
		createTiddlyText(place,caption);
	}
}

function onClickTiddlyPopup(ev)
{
	var e = ev || window.event;
	var tiddler = this.tiddler;
	if(tiddler.text) {
		var popup = Popup.create(this,"div","popupTiddler");
		wikify(tiddler.text,popup,null,tiddler);
		Popup.show();
	}
	if(e) e.cancelBubble = true;
	if(e && e.stopPropagation) e.stopPropagation();
	return false;
}

function createTiddlyError(place,title,text)
{
	var btn = createTiddlyButton(place,title,null,onClickError,"errorButton");
	if(text) btn.setAttribute("errorText",text);
}

function merge(dst,src,preserveExisting)
{
	for(var i in src) {
		if(!preserveExisting || dst[i] === undefined)
			dst[i] = src[i];
	}
	return dst;
}

// Returns a string containing the description of an exception, optionally prepended by a message
function exceptionText(e,message)
{
	var s = e.description || e.toString();
	return message ? "%0:\n%1".format([message,s]) : s;
}

// Displays an alert of an exception description with optional message
function showException(e,message)
{
	alert(exceptionText(e,message));
}

function alertAndThrow(m)
{
	alert(m);
	throw(m);
}

function glyph(name)
{
	var g = config.glyphs;
	var b = g.currBrowser;
	if(b == null) {
		b = 0;
		while(!g.browsers[b]() && b < g.browsers.length-1)
			b++;
		g.currBrowser = b;
	}
	if(!g.codes[name])
		return "";
	return g.codes[name][b];
}

if(!window.console) {
	console = {tiddlywiki:true,log:function(message) {displayMessage(message);}};
}

//-
//- Animation engine
//-

function Animator()
{
	this.running = 0; // Incremented at start of each animation, decremented afterwards. If zero, the interval timer is disabled
	this.timerID = 0; // ID of the timer used for animating
	this.animations = []; // List of animations in progress
	return this;
}

// Start animation engine
Animator.prototype.startAnimating = function() //# Variable number of arguments
{
	for(var t=0; t<arguments.length; t++)
		this.animations.push(arguments[t]);
	if(this.running == 0) {
		var me = this;
		this.timerID = window.setInterval(function() {me.doAnimate(me);},10);
	}
	this.running += arguments.length;
};

// Perform an animation engine tick, calling each of the known animation modules
Animator.prototype.doAnimate = function(me)
{
	var a = 0;
	while(a < me.animations.length) {
		var animation = me.animations[a];
		if(animation.tick()) {
			a++;
		} else {
			me.animations.splice(a,1);
			if(--me.running == 0)
				window.clearInterval(me.timerID);
		}
	}
};

Animator.slowInSlowOut = function(progress)
{
	return(1-((Math.cos(progress * Math.PI)+1)/2));
};

//--
//-- Morpher animation
//--

// Animate a set of properties of an element
function Morpher(element,duration,properties,callback)
{
	this.element = element;
	this.duration = duration;
	this.properties = properties;
	this.startTime = new Date();
	this.endTime = Number(this.startTime) + duration;
	this.callback = callback;
	this.tick();
	return this;
}

Morpher.prototype.assignStyle = function(element,style,value)
{
	switch(style) {
	case "-tw-vertScroll":
		window.scrollTo(findScrollX(),value);
		break;
	case "-tw-horizScroll":
		window.scrollTo(value,findScrollY());
		break;
	default:
		element.style[style] = value;
		break;
	}
};

Morpher.prototype.stop = function()
{
	for(var t=0; t<this.properties.length; t++) {
		var p = this.properties[t];
		if(p.atEnd !== undefined) {
			this.assignStyle(this.element,p.style,p.atEnd);
		}
	}
	if(this.callback)
		this.callback(this.element,this.properties);
};

Morpher.prototype.tick = function()
{
	var currTime = Number(new Date());
	var progress = Animator.slowInSlowOut(Math.min(1,(currTime-this.startTime)/this.duration));
	for(var t=0; t<this.properties.length; t++) {
		var p = this.properties[t];
		if(p.start !== undefined && p.end !== undefined) {
			var template = p.template || "%0";
			switch(p.format) {
			case undefined:
			case "style":
				var v = p.start + (p.end-p.start) * progress;
				this.assignStyle(this.element,p.style,template.format([v]));
				break;
			case "color":
				break;
			}
		}
	}
	if(currTime >= this.endTime) {
		this.stop();
		return false;
	}
	return true;
};

//--
//-- Zoomer animation
//--

function Zoomer(text,startElement,targetElement,unused)
{
	var e = createTiddlyElement(document.body,"div",null,"zoomer");
	createTiddlyElement(e,"div",null,null,text);
	var winWidth = findWindowWidth();
	var winHeight = findWindowHeight();
	var p = [
		{style: 'left', start: findPosX(startElement), end: findPosX(targetElement), template: '%0px'},
		{style: 'top', start: findPosY(startElement), end: findPosY(targetElement), template: '%0px'},
		{style: 'width', start: Math.min(startElement.scrollWidth,winWidth), end: Math.min(targetElement.scrollWidth,winWidth), template: '%0px', atEnd: 'auto'},
		{style: 'height', start: Math.min(startElement.scrollHeight,winHeight), end: Math.min(targetElement.scrollHeight,winHeight), template: '%0px', atEnd: 'auto'},
		{style: 'fontSize', start: 8, end: 24, template: '%0pt'}
	];
	var c = function(element,properties) {removeNode(element);};
	return new Morpher(e,config.animDuration,p,c);
}

//--
//-- Scroller animation
//--

function Scroller(targetElement)
{
	var p = [{style: '-tw-vertScroll', start: findScrollY(), end: ensureVisible(targetElement)}];
	return new Morpher(targetElement,config.animDuration,p);
}

//--
//-- Slider animation
//--

// deleteMode - "none", "all" [delete target element and it's children], [only] "children" [but not the target element]
function Slider(element,opening,unused,deleteMode)
{
	element.style.overflow = 'hidden';
	if(opening)
		element.style.height = '0px'; // Resolves a Firefox flashing bug
	element.style.display = 'block';
	var left = findPosX(element);
	var width = element.scrollWidth;
	var height = element.scrollHeight;
	var winWidth = findWindowWidth();
	var p = [];
	var c = null;
	if(opening) {
		p.push({style: 'height', start: 0, end: height, template: '%0px', atEnd: 'auto'});
		p.push({style: 'opacity', start: 0, end: 1, template: '%0'});
		p.push({style: 'filter', start: 0, end: 100, template: 'alpha(opacity:%0)'});
	} else {
		p.push({style: 'height', start: height, end: 0, template: '%0px'});
		p.push({style: 'display', atEnd: 'none'});
		p.push({style: 'opacity', start: 1, end: 0, template: '%0'});
		p.push({style: 'filter', start: 100, end: 0, template: 'alpha(opacity:%0)'});
		switch(deleteMode) {
		case "all":
			c = function(element,properties) {removeNode(element);};
			break;
		case "children":
			c = function(element,properties) {removeChildren(element);};
			break;
		}
	}
	return new Morpher(element,config.animDuration,p,c);
}

//--
//-- Popup menu
//--

var Popup = {
	stack: [] // Array of objects with members root: and popup:
	};

Popup.create = function(root,elem,className)
{
	var stackPosition = this.find(root,"popup");
	Popup.remove(stackPosition+1);
	var popup = createTiddlyElement(document.body,elem || "ol","popup",className || "popup");
	popup.stackPosition = stackPosition;
	Popup.stack.push({root: root, popup: popup});
	return popup;
};

Popup.onDocumentClick = function(ev)
{
	var e = ev || window.event;
	if(e.eventPhase == undefined)
		Popup.remove();
	else if(e.eventPhase == Event.BUBBLING_PHASE || e.eventPhase == Event.AT_TARGET)
		Popup.remove();
	return true;
};

Popup.show = function(valign,halign,offset)
{
	var curr = Popup.stack[Popup.stack.length-1];
	this.place(curr.root,curr.popup,valign,halign,offset);
	addClass(curr.root,"highlight");
	if(config.options.chkAnimate && anim && typeof Scroller == "function")
		anim.startAnimating(new Scroller(curr.popup));
	else
		window.scrollTo(0,ensureVisible(curr.popup));
};

Popup.place = function(root,popup,valign,halign,offset)
{
	if(!offset)
		var offset = {x:0,y:0};
	if(popup.stackPosition >= 0 && !valign && !halign) {
		offset.x = offset.x + root.offsetWidth;
	} else {
		offset.x = (halign == "right") ? offset.x + root.offsetWidth : offset.x;
		offset.y = (valign == "top") ? offset.y : offset.y + root.offsetHeight;
	}
	var rootLeft = findPosX(root);
	var rootTop = findPosY(root);
	var popupLeft = rootLeft + offset.x;
	var popupTop = rootTop + offset.y;
	var winWidth = findWindowWidth();
	if(popup.offsetWidth > winWidth*0.75)
		popup.style.width = winWidth*0.75 + "px";
	var popupWidth = popup.offsetWidth;
	var scrollWidth = winWidth - document.body.offsetWidth;
	if(popupLeft + popupWidth > winWidth - scrollWidth - 1) {
		if(halign == "right")
			popupLeft = popupLeft - root.offsetWidth - popupWidth;
		else
			popupLeft = winWidth - popupWidth - scrollWidth - 1;
	}
	popup.style.left = popupLeft + "px";
	popup.style.top = popupTop + "px";
	popup.style.display = "block";
};

Popup.find = function(e)
{
	var pos = -1;
	for (var t=this.stack.length-1; t>=0; t--) {
		if(isDescendant(e,this.stack[t].popup))
			pos = t;
	}
	return pos;
};

Popup.remove = function(pos)
{
	if(!pos) var pos = 0;
	if(Popup.stack.length > pos) {
		Popup.removeFrom(pos);
	}
};

Popup.removeFrom = function(from)
{
	for(var t=Popup.stack.length-1; t>=from; t--) {
		var p = Popup.stack[t];
		removeClass(p.root,"highlight");
		removeNode(p.popup);
	}
	Popup.stack = Popup.stack.slice(0,from);
};

//--
//-- Wizard support
//--

function Wizard(elem)
{
	if(elem) {
		this.formElem = findRelated(elem,"wizard","className");
		this.bodyElem = findRelated(this.formElem.firstChild,"wizardBody","className","nextSibling");
		this.footElem = findRelated(this.formElem.firstChild,"wizardFooter","className","nextSibling");
	} else {
		this.formElem = null;
		this.bodyElem = null;
		this.footElem = null;
	}
}

Wizard.prototype.setValue = function(name,value)
{
	if(this.formElem)
		this.formElem[name] = value;
};

Wizard.prototype.getValue = function(name)
{
	return this.formElem ? this.formElem[name] : null;
};

Wizard.prototype.createWizard = function(place,title)
{
	this.formElem = createTiddlyElement(place,"form",null,"wizard");
	createTiddlyElement(this.formElem,"h1",null,null,title);
	this.bodyElem = createTiddlyElement(this.formElem,"div",null,"wizardBody");
	this.footElem = createTiddlyElement(this.formElem,"div",null,"wizardFooter");
	return this.formElem;
};

Wizard.prototype.clear = function()
{
	removeChildren(this.bodyElem);
};

Wizard.prototype.setButtons = function(buttonInfo,status)
{
	removeChildren(this.footElem);
	for(var t=0; t<buttonInfo.length; t++) {
		createTiddlyButton(this.footElem,buttonInfo[t].caption,buttonInfo[t].tooltip,buttonInfo[t].onClick);
		insertSpacer(this.footElem);
		}
	if(typeof status == "string") {
		createTiddlyElement(this.footElem,"span",null,"status",status);
	}
};

Wizard.prototype.addStep = function(stepTitle,html)
{
	removeChildren(this.bodyElem);
	var w = createTiddlyElement(this.bodyElem,"div");
	createTiddlyElement(w,"h2",null,null,stepTitle);
	var step = createTiddlyElement(w,"div",null,"wizardStep");
	step.innerHTML = html;
	applyHtmlMacros(step,tiddler);
};

Wizard.prototype.getElement = function(name)
{
	return this.formElem.elements[name];
};

//--
//-- ListView gadget
//--

var ListView = {};

// Create a listview
ListView.create = function(place,listObject,listTemplate,callback,className)
{
	var table = createTiddlyElement(place,"table",null,className || "listView twtable");
	var thead = createTiddlyElement(table,"thead");
	var r = createTiddlyElement(thead,"tr");
	for(var t=0; t<listTemplate.columns.length; t++) {
		var columnTemplate = listTemplate.columns[t];
		var c = createTiddlyElement(r,"th");
		var colType = ListView.columnTypes[columnTemplate.type];
		if(colType && colType.createHeader) {
			colType.createHeader(c,columnTemplate,t);
			if(columnTemplate.className)
				addClass(c,columnTemplate.className);
		}
	}
	var tbody = createTiddlyElement(table,"tbody");
	for(var rc=0; rc<listObject.length; rc++) {
		var rowObject = listObject[rc];
		r = createTiddlyElement(tbody,"tr");
		for(c=0; c<listTemplate.rowClasses.length; c++) {
			if(rowObject[listTemplate.rowClasses[c].field])
				addClass(r,listTemplate.rowClasses[c].className);
		}
		rowObject.rowElement = r;
		rowObject.colElements = {};
		for(var cc=0; cc<listTemplate.columns.length; cc++) {
			c = createTiddlyElement(r,"td");
			columnTemplate = listTemplate.columns[cc];
			var field = columnTemplate.field;
			colType = ListView.columnTypes[columnTemplate.type];
			if(colType && colType.createItem) {
				colType.createItem(c,rowObject,field,columnTemplate,cc,rc);
				if(columnTemplate.className)
					addClass(c,columnTemplate.className);
			}
			rowObject.colElements[field] = c;
		}
	}
	if(callback && listTemplate.actions)
		createTiddlyDropDown(place,ListView.getCommandHandler(callback),listTemplate.actions);
	if(callback && listTemplate.buttons) {
		for(t=0; t<listTemplate.buttons.length; t++) {
			var a = listTemplate.buttons[t];
			if(a && a.name != "")
				createTiddlyButton(place,a.caption,null,ListView.getCommandHandler(callback,a.name,a.allowEmptySelection));
		}
	}
	return table;
};

ListView.getCommandHandler = function(callback,name,allowEmptySelection)
{
	return function(e) {
		var view = findRelated(this,"TABLE",null,"previousSibling");
		var tiddlers = [];
		ListView.forEachSelector(view,function(e,rowName) {
					if(e.checked)
						tiddlers.push(rowName);
					});
		if(tiddlers.length == 0 && !allowEmptySelection) {
			alert(config.messages.nothingSelected);
		} else {
			if(this.nodeName.toLowerCase() == "select") {
				callback(view,this.value,tiddlers);
				this.selectedIndex = 0;
			} else {
				callback(view,name,tiddlers);
			}
		}
	};
};

// Invoke a callback for each selector checkbox in the listview
ListView.forEachSelector = function(view,callback)
{
	var checkboxes = view.getElementsByTagName("input");
	var hadOne = false;
	for(var t=0; t<checkboxes.length; t++) {
		var cb = checkboxes[t];
		if(cb.getAttribute("type") == "checkbox") {
			var rn = cb.getAttribute("rowName");
			if(rn) {
				callback(cb,rn);
				hadOne = true;
			}
		}
	}
	return hadOne;
};

ListView.getSelectedRows = function(view)
{
	var rowNames = [];
	ListView.forEachSelector(view,function(e,rowName) {
				if(e.checked)
					rowNames.push(rowName);
				});
	return rowNames;
};

ListView.columnTypes = {};

ListView.columnTypes.String = {
	createHeader: function(place,columnTemplate,col)
		{
			createTiddlyText(place,columnTemplate.title);
		},
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined)
				createTiddlyText(place,v);
		}
};

ListView.columnTypes.WikiText = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined)
				wikify(v,place,null,null);
		}
};

ListView.columnTypes.Tiddler = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined && v.title)
				createTiddlyPopup(place,v.title,config.messages.listView.tiddlerTooltip,v);
		}
};

ListView.columnTypes.Size = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var msg = config.messages.sizeTemplates;
			var v = listObject[field];
			if(v != undefined) {
				var t = 0;
				while(t<msg.length-1 && v<msg[t].unit)
					t++;
				createTiddlyText(place,msg[t].template.format([Math.round(v/msg[t].unit)]));
			}
		}
};

ListView.columnTypes.Link = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			var c = columnTemplate.text;
			if(v != undefined)
				createExternalLink(place,v,c || v);
		}
};

ListView.columnTypes.Date = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined)
				createTiddlyText(place,v.formatString(columnTemplate.dateFormat));
		}
};

ListView.columnTypes.StringList = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined) {
				for(var t=0; t<v.length; t++) {
					createTiddlyText(place,v[t]);
					createTiddlyElement(place,"br");
				}
			}
		}
};

ListView.columnTypes.Selector = {
	createHeader: function(place,columnTemplate,col)
		{
			createTiddlyCheckbox(place,null,false,this.onHeaderChange);
		},
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var e = createTiddlyCheckbox(place,null,listObject[field],null);
			e.setAttribute("rowName",listObject[columnTemplate.rowName]);
		},
	onHeaderChange: function(e)
		{
			var state = this.checked;
			var view = findRelated(this,"TABLE");
			if(!view)
				return;
			ListView.forEachSelector(view,function(e,rowName) {
								e.checked = state;
							});
		}
};

ListView.columnTypes.Tags = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var tags = listObject[field];
			createTiddlyText(place,String.encodeTiddlyLinkList(tags));
		}
};

ListView.columnTypes.Boolean = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			if(listObject[field] == true)
				createTiddlyText(place,columnTemplate.trueText);
			if(listObject[field] == false)
				createTiddlyText(place,columnTemplate.falseText);
		}
};

ListView.columnTypes.TagCheckbox = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var e = createTiddlyCheckbox(place,null,listObject[field],this.onChange);
			e.setAttribute("tiddler",listObject.title);
			e.setAttribute("tag",columnTemplate.tag);
		},
	onChange : function(e)
		{
			var tag = this.getAttribute("tag");
			var tiddler = this.getAttribute("tiddler");
			store.setTiddlerTag(tiddler,this.checked,tag);
		}
};

ListView.columnTypes.TiddlerLink = {
	createHeader: ListView.columnTypes.String.createHeader,
	createItem: function(place,listObject,field,columnTemplate,col,row)
		{
			var v = listObject[field];
			if(v != undefined) {
				var link = createTiddlyLink(place,listObject[columnTemplate.tiddlerLink],false,null);
				createTiddlyText(link,listObject[field]);
			}
		}
};

//--
//-- Augmented methods for the JavaScript Number(), Array(), String() and Date() objects
//--

// Clamp a number to a range
Number.prototype.clamp = function(min,max)
{
	var c = this;
	if(c < min)
		c = min;
	if(c > max)
		c = max;
	return Number(c);
};

// Add indexOf function if browser does not support it
if(!Array.indexOf) {
Array.prototype.indexOf = function(item,from)
{
	if(!from)
		from = 0;
	for(var i=from; i<this.length; i++) {
		if(this[i] === item)
			return i;
	}
	return -1;
};}

// Find an entry in a given field of the members of an array
Array.prototype.findByField = function(field,value)
{
	for(var t=0; t<this.length; t++) {
		if(this[t][field] === value)
			return t;
	}
	return null;
};

// Return whether an entry exists in an array
Array.prototype.contains = function(item)
{
	return this.indexOf(item) != -1;
};

// Adds, removes or toggles a particular value within an array
//  value - value to add
//  mode - +1 to add value, -1 to remove value, 0 to toggle it
Array.prototype.setItem = function(value,mode)
{
	var p = this.indexOf(value);
	if(mode == 0)
		mode = (p == -1) ? +1 : -1;
	if(mode == +1) {
		if(p == -1)
			this.push(value);
	} else if(mode == -1) {
		if(p != -1)
			this.splice(p,1);
	}
};

// Return whether one of a list of values exists in an array
Array.prototype.containsAny = function(items)
{
	for(var i=0; i<items.length; i++) {
		if(this.indexOf(items[i]) != -1)
			return true;
	}
	return false;
};

// Return whether all of a list of values exists in an array
Array.prototype.containsAll = function(items)
{
	for(var i = 0; i<items.length; i++) {
		if(this.indexOf(items[i]) == -1)
			return false;
	}
	return true;
};

// Push a new value into an array only if it is not already present in the array. If the optional unique parameter is false, it reverts to a normal push
Array.prototype.pushUnique = function(item,unique)
{
	if(unique === false) {
		this.push(item);
	} else {
		if(this.indexOf(item) == -1)
			this.push(item);
	}
};

Array.prototype.remove = function(item)
{
	var p = this.indexOf(item);
	if(p != -1)
		this.splice(p,1);
};

if(!Array.prototype.map) {
Array.prototype.map = function(fn,thisObj)
{
	var scope = thisObj || window;
	var a = [];
	for(var i=0, j=this.length; i < j; ++i) {
		a.push(fn.call(scope,this[i],i,this));
	}
	return a;
};}

// Get characters from the right end of a string
String.prototype.right = function(n)
{
	return n < this.length ? this.slice(this.length-n) : this;
};

// Trim whitespace from both ends of a string
String.prototype.trim = function()
{
	return this.replace(/^\s*|\s*$/g,"");
};

// Convert a string from a CSS style property name to a JavaScript style name ("background-color" -> "backgroundColor")
String.prototype.unDash = function()
{
	var s = this.split("-");
	if(s.length > 1) {
		for(var t=1; t<s.length; t++)
			s[t] = s[t].substr(0,1).toUpperCase() + s[t].substr(1);
	}
	return s.join("");
};

// Substitute substrings from an array into a format string that includes '%1'-type specifiers
String.prototype.format = function(s)
{
	var substrings = s && s.constructor == Array ? s : arguments;
	var subRegExp = /(?:%(\d+))/mg;
	var currPos = 0;
	var r = [];
	do {
		var match = subRegExp.exec(this);
		if(match && match[1]) {
			if(match.index > currPos)
				r.push(this.substring(currPos,match.index));
			r.push(substrings[parseInt(match[1])]);
			currPos = subRegExp.lastIndex;
		}
	} while(match);
	if(currPos < this.length)
		r.push(this.substring(currPos,this.length));
	return r.join("");
};

// Escape any special RegExp characters with that character preceded by a backslash
String.prototype.escapeRegExp = function()
{
	var s = "\\^$*+?()=!|,{}[].";
	var c = this;
	for(var t=0; t<s.length; t++)
		c = c.replace(new RegExp("\\" + s.substr(t,1),"g"),"\\" + s.substr(t,1));
	return c;
};

// Convert "\" to "\s", newlines to "\n" (and remove carriage returns)
String.prototype.escapeLineBreaks = function()
{
	return this.replace(/\\/mg,"\\s").replace(/\n/mg,"\\n").replace(/\r/mg,"");
};

// Convert "\n" to newlines, "\b" to " ", "\s" to "\" (and remove carriage returns)
String.prototype.unescapeLineBreaks = function()
{
	return this.replace(/\\n/mg,"\n").replace(/\\b/mg," ").replace(/\\s/mg,"\\").replace(/\r/mg,"");
};

// Convert & to "&amp;", < to "&lt;", > to "&gt;" and " to "&quot;"
String.prototype.htmlEncode = function()
{
	return this.replace(/&/mg,"&amp;").replace(/</mg,"&lt;").replace(/>/mg,"&gt;").replace(/\"/mg,"&quot;");
};

// Convert "&amp;" to &, "&lt;" to <, "&gt;" to > and "&quot;" to "
String.prototype.htmlDecode = function()
{
	return this.replace(/&lt;/mg,"<").replace(/&gt;/mg,">").replace(/&quot;/mg,"\"").replace(/&amp;/mg,"&");
};

// Parse a space-separated string of name:value parameters
// The result is an array of objects:
//   result[0] = object with a member for each parameter name, value of that member being an array of values
//   result[1..n] = one object for each parameter, with 'name' and 'value' members
String.prototype.parseParams = function(defaultName,defaultValue,allowEval,noNames,cascadeDefaults)
{
	var parseToken = function(match,p) {
		var n;
		if(match[p]) // Double quoted
			n = match[p];
		else if(match[p+1]) // Single quoted
			n = match[p+1];
		else if(match[p+2]) // Double-square-bracket quoted
			n = match[p+2];
		else if(match[p+3]) // Double-brace quoted
			try {
				n = match[p+3];
				if(allowEval && config.evaluateMacroParameters != "none") {
					if(config.evaluateMacroParameters == "restricted") {
						if(window.restrictedEval) {
							n = window.restrictedEval(n);
						}
					} else {
						n = window.eval(n);
					}
				}
			} catch(ex) {
				throw "Unable to evaluate {{" + match[p+3] + "}}: " + exceptionText(ex);
			}
		else if(match[p+4]) // Unquoted
			n = match[p+4];
		else if(match[p+5]) // empty quote
			n = "";
		return n;
	};
	var r = [{}];
	var dblQuote = "(?:\"((?:(?:\\\\\")|[^\"])+)\")";
	var sngQuote = "(?:'((?:(?:\\\\\')|[^'])+)')";
	var dblSquare = "(?:\\[\\[((?:\\s|\\S)*?)\\]\\])";
	var dblBrace = "(?:\\{\\{((?:\\s|\\S)*?)\\}\\})";
	var unQuoted = noNames ? "([^\"'\\s]\\S*)" : "([^\"':\\s][^\\s:]*)";
	var emptyQuote = "((?:\"\")|(?:''))";
	var skipSpace = "(?:\\s*)";
	var token = "(?:" + dblQuote + "|" + sngQuote + "|" + dblSquare + "|" + dblBrace + "|" + unQuoted + "|" + emptyQuote + ")";
	var re = noNames ? new RegExp(token,"mg") : new RegExp(skipSpace + token + skipSpace + "(?:(\\:)" + skipSpace + token + ")?","mg");
	var params = [];
	do {
		var match = re.exec(this);
		if(match) {
			var n = parseToken(match,1);
			if(noNames) {
				r.push({name:"",value:n});
			} else {
				var v = parseToken(match,8);
				if(v == null && defaultName) {
					v = n;
					n = defaultName;
				} else if(v == null && defaultValue) {
					v = defaultValue;
				}
				r.push({name:n,value:v});
				if(cascadeDefaults) {
					defaultName = n;
					defaultValue = v;
				}
			}
		}
	} while(match);
	// Summarise parameters into first element
	for(var t=1; t<r.length; t++) {
		if(r[0][r[t].name])
			r[0][r[t].name].push(r[t].value);
		else
			r[0][r[t].name] = [r[t].value];
	}
	return r;
};

// Process a string list of macro parameters into an array. Parameters can be quoted with "", '',
// [[]], {{ }} or left unquoted (and therefore space-separated). Double-braces {{}} results in
// an *evaluated* parameter: e.g. {{config.options.txtUserName}} results in the current user's name.
String.prototype.readMacroParams = function(notAllowEval)
{
	var p = this.parseParams("list",null,!notAllowEval,true);
	var n = [];
	for(var t=1; t<p.length; t++)
		n.push(p[t].value);
	return n;
};

// Process a string list of unique tiddler names into an array. Tiddler names that have spaces in them must be [[bracketed]]
String.prototype.readBracketedList = function(unique)
{
	var p = this.parseParams("list",null,false,true);
	var n = [];
	for(var t=1; t<p.length; t++) {
		if(p[t].value)
			n.pushUnique(p[t].value,unique);
	}
	return n;
};

// Returns array with start and end index of chunk between given start and end marker, or undefined.
String.prototype.getChunkRange = function(start,end)
{
	var s = this.indexOf(start);
	if(s != -1) {
		s += start.length;
		var e = this.indexOf(end,s);
		if(e != -1)
			return [s,e];
	}
};

// Replace a chunk of a string given start and end markers
String.prototype.replaceChunk = function(start,end,sub)
{
	var r = this.getChunkRange(start,end);
	return r ? this.substring(0,r[0]) + sub + this.substring(r[1]) : this;
};

// Returns a chunk of a string between start and end markers, or undefined
String.prototype.getChunk = function(start,end)
{
	var r = this.getChunkRange(start,end);
	if(r)
		return this.substring(r[0],r[1]);
};


// Static method to bracket a string with double square brackets if it contains a space
String.encodeTiddlyLink = function(title)
{
	return title.indexOf(" ") == -1 ? title : "[[" + title + "]]";
};

// Static method to encodeTiddlyLink for every item in an array and join them with spaces
String.encodeTiddlyLinkList = function(list)
{
	if(list) {
		var results = [];
		for(var t=0; t<list.length; t++)
			results.push(String.encodeTiddlyLink(list[t]));
		return results.join(" ");
	} else {
		return "";
	}
};

// Convert a string as a sequence of name:"value" pairs into a hashmap
String.prototype.decodeHashMap = function()
{
	var fields = this.parseParams("anon","",false);
	var r = {};
	for(var t=1; t<fields.length; t++)
		r[fields[t].name] = fields[t].value;
	return r;
};

// Static method to encode a hashmap into a name:"value"... string
String.encodeHashMap = function(hashmap)
{
	var r = [];
	for(var t in hashmap)
		r.push(t + ':"' + hashmap[t] + '"');
	return r.join(" ");
};

// Static method to left-pad a string with 0s to a certain width
String.zeroPad = function(n,d)
{
	var s = n.toString();
	if(s.length < d)
		s = "000000000000000000000000000".substr(0,d-s.length) + s;
	return s;
};

String.prototype.startsWith = function(prefix)
{
	return !prefix || this.substring(0,prefix.length) == prefix;
};

// Returns the first value of the given named parameter.
function getParam(params,name,defaultValue)
{
	if(!params)
		return defaultValue;
	var p = params[0][name];
	return p ? p[0] : defaultValue;
}

// Returns the first value of the given boolean named parameter.
function getFlag(params,name,defaultValue)
{
	return !!getParam(params,name,defaultValue);
}

// Substitute date components into a string
Date.prototype.formatString = function(template)
{
	var t = template.replace(/0hh12/g,String.zeroPad(this.getHours12(),2));
	t = t.replace(/hh12/g,this.getHours12());
	t = t.replace(/0hh/g,String.zeroPad(this.getHours(),2));
	t = t.replace(/hh/g,this.getHours());
	t = t.replace(/mmm/g,config.messages.dates.shortMonths[this.getMonth()]);
	t = t.replace(/0mm/g,String.zeroPad(this.getMinutes(),2));
	t = t.replace(/mm/g,this.getMinutes());
	t = t.replace(/0ss/g,String.zeroPad(this.getSeconds(),2));
	t = t.replace(/ss/g,this.getSeconds());
	t = t.replace(/[ap]m/g,this.getAmPm().toLowerCase());
	t = t.replace(/[AP]M/g,this.getAmPm().toUpperCase());
	t = t.replace(/wYYYY/g,this.getYearForWeekNo());
	t = t.replace(/wYY/g,String.zeroPad(this.getYearForWeekNo()-2000,2));
	t = t.replace(/YYYY/g,this.getFullYear());
	t = t.replace(/YY/g,String.zeroPad(this.getFullYear()-2000,2));
	t = t.replace(/MMM/g,config.messages.dates.months[this.getMonth()]);
	t = t.replace(/0MM/g,String.zeroPad(this.getMonth()+1,2));
	t = t.replace(/MM/g,this.getMonth()+1);
	t = t.replace(/0WW/g,String.zeroPad(this.getWeek(),2));
	t = t.replace(/WW/g,this.getWeek());
	t = t.replace(/DDD/g,config.messages.dates.days[this.getDay()]);
	t = t.replace(/ddd/g,config.messages.dates.shortDays[this.getDay()]);
	t = t.replace(/0DD/g,String.zeroPad(this.getDate(),2));
	t = t.replace(/DDth/g,this.getDate()+this.daySuffix());
	t = t.replace(/DD/g,this.getDate());
	var tz = this.getTimezoneOffset();
	var atz = Math.abs(tz);
	t = t.replace(/TZD/g,(tz < 0 ? '+' : '-') + String.zeroPad(Math.floor(atz / 60),2) + ':' + String.zeroPad(atz % 60,2));
	t = t.replace(/\\/g,"");
	return t;
};

Date.prototype.getWeek = function()
{
	var dt = new Date(this.getTime());
	var d = dt.getDay();
	if(d==0) d=7;// JavaScript Sun=0, ISO Sun=7
	dt.setTime(dt.getTime()+(4-d)*86400000);// shift day to Thurs of same week to calculate weekNo
	var n = Math.floor((dt.getTime()-new Date(dt.getFullYear(),0,1)+3600000)/86400000);
	return Math.floor(n/7)+1;
};

Date.prototype.getYearForWeekNo = function()
{
	var dt = new Date(this.getTime());
	var d = dt.getDay();
	if(d==0) d=7;// JavaScript Sun=0, ISO Sun=7
	dt.setTime(dt.getTime()+(4-d)*86400000);// shift day to Thurs of same week
	return dt.getFullYear();
};

Date.prototype.getHours12 = function()
{
	var h = this.getHours();
	return h > 12 ? h-12 : ( h > 0 ? h : 12 );
};

Date.prototype.getAmPm = function()
{
	return this.getHours() >= 12 ? config.messages.dates.pm : config.messages.dates.am;
};

Date.prototype.daySuffix = function()
{
	return config.messages.dates.daySuffixes[this.getDate()-1];
};

// Convert a date to local YYYYMMDDHHMM string format
Date.prototype.convertToLocalYYYYMMDDHHMM = function()
{
	return this.getFullYear() + String.zeroPad(this.getMonth()+1,2) + String.zeroPad(this.getDate(),2) + String.zeroPad(this.getHours(),2) + String.zeroPad(this.getMinutes(),2);
};

// Convert a date to UTC YYYYMMDDHHMM string format
Date.prototype.convertToYYYYMMDDHHMM = function()
{
	return this.getUTCFullYear() + String.zeroPad(this.getUTCMonth()+1,2) + String.zeroPad(this.getUTCDate(),2) + String.zeroPad(this.getUTCHours(),2) + String.zeroPad(this.getUTCMinutes(),2);
};

// Convert a date to UTC YYYYMMDD.HHMMSSMMM string format
Date.prototype.convertToYYYYMMDDHHMMSSMMM = function()
{
	return this.getUTCFullYear() + String.zeroPad(this.getUTCMonth()+1,2) + String.zeroPad(this.getUTCDate(),2) + "." + String.zeroPad(this.getUTCHours(),2) + String.zeroPad(this.getUTCMinutes(),2) + String.zeroPad(this.getUTCSeconds(),2) + String.zeroPad(this.getUTCMilliseconds(),3) +"0";
};

// Static method to create a date from a UTC YYYYMMDDHHMM format string
Date.convertFromYYYYMMDDHHMM = function(d)
{
	d = d?d.replace(/[^0-9]/g, ""):"";
	return Date.convertFromYYYYMMDDHHMMSSMMM(d.substr(0,12));
};

// Static method to create a date from a UTC YYYYMMDDHHMMSS format string
Date.convertFromYYYYMMDDHHMMSS = function(d)
{
	d = d?d.replace(/[^0-9]/g, ""):"";
	return Date.convertFromYYYYMMDDHHMMSSMMM(d.substr(0,14));
};

// Static method to create a date from a UTC YYYYMMDDHHMMSSMMM format string
Date.convertFromYYYYMMDDHHMMSSMMM = function(d)
{
	d = d ? d.replace(/[^0-9]/g, "") : "";
	return new Date(Date.UTC(parseInt(d.substr(0,4),10),
			parseInt(d.substr(4,2),10)-1,
			parseInt(d.substr(6,2),10),
			parseInt(d.substr(8,2)||"00",10),
			parseInt(d.substr(10,2)||"00",10),
			parseInt(d.substr(12,2)||"00",10),
			parseInt(d.substr(14,3)||"000",10)));
};

//--
//-- RGB colour object
//--

// Construct an RGB colour object from a '#rrggbb', '#rgb' or 'rgb(n,n,n)' string or from separate r,g,b values
function RGB(r,g,b)
{
	this.r = 0;
	this.g = 0;
	this.b = 0;
	if(typeof r == "string") {
		if(r.substr(0,1) == "#") {
			if(r.length == 7) {
				this.r = parseInt(r.substr(1,2),16)/255;
				this.g = parseInt(r.substr(3,2),16)/255;
				this.b = parseInt(r.substr(5,2),16)/255;
			} else {
				this.r = parseInt(r.substr(1,1),16)/15;
				this.g = parseInt(r.substr(2,1),16)/15;
				this.b = parseInt(r.substr(3,1),16)/15;
			}
		} else {
			var rgbPattern = /rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/;
			var c = r.match(rgbPattern);
			if(c) {
				this.r = parseInt(c[1],10)/255;
				this.g = parseInt(c[2],10)/255;
				this.b = parseInt(c[3],10)/255;
			}
		}
	} else {
		this.r = r;
		this.g = g;
		this.b = b;
	}
	return this;
}

// Mixes this colour with another in a specified proportion
// c = other colour to mix
// f = 0..1 where 0 is this colour and 1 is the new colour
// Returns an RGB object
RGB.prototype.mix = function(c,f)
{
	return new RGB(this.r + (c.r-this.r) * f,this.g + (c.g-this.g) * f,this.b + (c.b-this.b) * f);
};

// Return an rgb colour as a #rrggbb format hex string
RGB.prototype.toString = function()
{
	return "#" + ("0" + Math.floor(this.r.clamp(0,1) * 255).toString(16)).right(2) +
				("0" + Math.floor(this.g.clamp(0,1) * 255).toString(16)).right(2) +
				("0" + Math.floor(this.b.clamp(0,1) * 255).toString(16)).right(2);
};

//--
//-- DOM utilities - many derived from www.quirksmode.org
//--

// Resolve the target object of an event
function resolveTarget(e)
{
	var obj;
	if(e.target)
		obj = e.target;
	else if(e.srcElement)
		obj = e.srcElement;
	if(obj.nodeType == 3) // defeat Safari bug
		obj = obj.parentNode;
	return obj;
}

function drawGradient(place,horiz,locolors,hicolors)
{
	if(!hicolors)
		hicolors = locolors;
	for(var t=0; t<= 100; t+=2) {
		var bar = document.createElement("div");
		place.appendChild(bar);
		bar.style.position = "absolute";
		bar.style.left = horiz ? t + "%" : 0;
		bar.style.top = horiz ? 0 : t + "%";
		bar.style.width = horiz ? (101-t) + "%" : "100%";
		bar.style.height = horiz ? "100%" : (101-t) + "%";
		bar.style.zIndex = -1;
		var p = t/100*(locolors.length-1);
		var hc = hicolors[Math.floor(p)];
		if(typeof hc == "string")
			hc = new RGB(hc);
		var lc = locolors[Math.ceil(p)];
		if(typeof lc == "string")
			lc = new RGB(lc);
		bar.style.backgroundColor = hc.mix(lc,p-Math.floor(p)).toString();
	}
}

function createTiddlyText(parent,text)
{
	return parent.appendChild(document.createTextNode(text));
}

function createTiddlyCheckbox(parent,caption,checked,onChange)
{
	var cb = document.createElement("input");
	cb.setAttribute("type","checkbox");
	cb.onclick = onChange;
	parent.appendChild(cb);
	cb.checked = checked;
	cb.className = "chkOptionInput";
	if(caption)
		wikify(caption,parent);
	return cb;
}

function createTiddlyElement(parent,element,id,className,text,attribs)
{
	var e = document.createElement(element);
	if(className != null)
		e.className = className;
	if(id != null)
		e.setAttribute("id",id);
	if(text != null)
		e.appendChild(document.createTextNode(text));
	if(attribs) {
		for(var n in attribs) {
			e.setAttribute(n,attribs[n]);
		}
	}
	if(parent != null)
		parent.appendChild(e);
	return e;
}

function addEvent(obj,type,fn)
{
	if(obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function(){obj["e"+type+fn](window.event);};
		obj.attachEvent("on"+type,obj[type+fn]);
	} else {
		obj.addEventListener(type,fn,false);
	}
}

function removeEvent(obj,type,fn)
{
	if(obj.detachEvent) {
		obj.detachEvent("on"+type,obj[type+fn]);
		obj[type+fn] = null;
	} else {
		obj.removeEventListener(type,fn,false);
	}
}


// Find the closest relative with a given property value (property defaults to tagName, relative defaults to parentNode)
function findRelated(e,value,name,relative)
{
	name = name || "tagName";
	relative = relative || "parentNode";
	if(name == "className") {
		while(e && !hasClass(e,value)) {
			e = e[relative];
		}
	} else {
		while(e && e[name] != value) {
			e = e[relative];
		}
	}
	return e;
}

// Get the scroll position for window.scrollTo necessary to scroll a given element into view
function ensureVisible(e)
{
	var posTop = findPosY(e);
	var posBot = posTop + e.offsetHeight;
	var winTop = findScrollY();
	var winHeight = findWindowHeight();
	var winBot = winTop + winHeight;
	if(posTop < winTop) {
		return posTop;
	} else if(posBot > winBot) {
		if(e.offsetHeight < winHeight)
			return posTop - (winHeight - e.offsetHeight);
		else
			return posTop;
	} else {
		return winTop;
	}
}

// Get the current width of the display window
function findWindowWidth()
{
	return window.innerWidth || document.documentElement.clientWidth;
}

// Get the current height of the display window
function findWindowHeight()
{
	return window.innerHeight || document.documentElement.clientHeight;
}

// Get the current horizontal page scroll position
function findScrollX()
{
	return window.scrollX || document.documentElement.scrollLeft;
}

// Get the current vertical page scroll position
function findScrollY()
{
	return window.scrollY || document.documentElement.scrollTop;
}

function findPosX(obj)
{
	var curleft = 0;
	while(obj.offsetParent) {
		curleft += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	while(obj.offsetParent) {
		curtop += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return curtop;
}

// Blur a particular element
function blurElement(e)
{
	if(e && e.focus && e.blur) {
		e.focus();
		e.blur();
	}
}

// Create a non-breaking space
function insertSpacer(place)
{
	var e = document.createTextNode(String.fromCharCode(160));
	if(place)
		place.appendChild(e);
	return e;
}

// Force the browser to do a document reflow when needed to workaround browser bugs
function forceReflow()
{
	if(config.browser.isGecko) {
		setStylesheet("body {top:0px;margin-top:0px;}","forceReflow");
		setTimeout(function() {setStylesheet("","forceReflow");},1);
	}
}

// Replace the current selection of a textarea or text input and scroll it into view
function replaceSelection(e,text)
{
	if(e.setSelectionRange) {
		var oldpos = e.selectionStart;
		var isRange = e.selectionEnd > e.selectionStart;
		e.value = e.value.substr(0,e.selectionStart) + text + e.value.substr(e.selectionEnd);
		e.setSelectionRange(isRange ? oldpos : oldpos + text.length,oldpos + text.length);
		var linecount = e.value.split("\n").length;
		var thisline = e.value.substr(0,e.selectionStart).split("\n").length-1;
		e.scrollTop = Math.floor((thisline - e.rows / 2) * e.scrollHeight / linecount);
	} else if(document.selection) {
		var range = document.selection.createRange();
		if(range.parentElement() == e) {
			var isCollapsed = range.text == "";
			range.text = text;
			if(!isCollapsed) {
				range.moveStart("character", -text.length);
				range.select();
			}
		}
	}
}

// Set the caret position in a text area
function setCaretPosition(e,pos)
{
	if(e.selectionStart || e.selectionStart == '0') {
		e.selectionStart = pos;
		e.selectionEnd = pos;
		e.focus();
	} else if(document.selection) {
		// IE support
		e.focus ();
		var sel = document.selection.createRange();
		sel.moveStart('character', -e.value.length);
		sel.moveStart('character',pos);
		sel.moveEnd('character',0);
		sel.select();
	}
}

// Returns the text of the given (text) node, possibly merging subsequent text nodes
function getNodeText(e)
{
	var t = "";
	while(e && e.nodeName == "#text") {
		t += e.nodeValue;
		e = e.nextSibling;
	}
	return t;
}

// Returns true if the element e has a given ancestor element
function isDescendant(e,ancestor)
{
	while(e) {
		if(e === ancestor)
			return true;
		e = e.parentNode;
	}
	return false;
}


// deprecate the following...

// Prevent an event from bubbling
function stopEvent(e)
{
	var ev = e || window.event;
	ev.cancelBubble = true;
	if(ev.stopPropagation) ev.stopPropagation();
	return false;
}

// Remove any event handlers or non-primitve custom attributes
function scrubNode(e)
{
	if(!config.browser.isIE)
		return;
	var att = e.attributes;
	if(att) {
		for(var t=0; t<att.length; t++) {
			var n = att[t].name;
			if(n !== "style" && (typeof e[n] === "function" || (typeof e[n] === "object" && e[n] != null))) {
				try {
					e[n] = null;
				} catch(ex) {
				}
			}
		}
	}
	var c = e.firstChild;
	while(c) {
		scrubNode(c);
		c = c.nextSibling;
	}
}

function addClass(e,className)
{
	jQuery(e).addClass(className);
}

function removeClass(e,className)
{
	jQuery(e).removeClass(className);
}

function hasClass(e,className)
{
	return jQuery(e).hasClass(className);
}

// Remove all children of a node
function removeChildren(e)
{
	jQuery(e).empty();
}

// Return the content of an element as plain text with no formatting
function getPlainText(e)
{
	return jQuery(e).text();
}

// Remove a node and all it's children
function removeNode(e)
{
	jQuery(e).remove();
}

//--
//-- LoaderBase and SaverBase
//--

function LoaderBase() {}

LoaderBase.prototype.loadTiddler = function(store,node,tiddlers)
{
	var title = this.getTitle(store,node);
	if(safeMode && store.isShadowTiddler(title))
		return;
	if(title) {
		var tiddler = store.createTiddler(title);
		this.internalizeTiddler(store,tiddler,title,node);
		tiddlers.push(tiddler);
	}
};

LoaderBase.prototype.loadTiddlers = function(store,nodes)
{
	var tiddlers = [];
	for(var t = 0; t < nodes.length; t++) {
		try {
			this.loadTiddler(store,nodes[t],tiddlers);
		} catch(ex) {
			showException(ex,config.messages.tiddlerLoadError.format([this.getTitle(store,nodes[t])]));
		}
	}
	return tiddlers;
};

function SaverBase() {}

SaverBase.prototype.externalize = function(store)
{
	var results = [];
	var tiddlers = store.getTiddlers("title");
	for(var t = 0; t < tiddlers.length; t++) {
		if(!tiddlers[t].doNotSave())
			results.push(this.externalizeTiddler(store, tiddlers[t]));
	}
	return results.join("\n");
};

//--
//-- TW21Loader (inherits from LoaderBase)
//--

function TW21Loader() {}

TW21Loader.prototype = new LoaderBase();

TW21Loader.prototype.getTitle = function(store,node)
{
	var title = null;
	if(node.getAttribute) {
		title = node.getAttribute("title");
		if(!title)
			title = node.getAttribute("tiddler");
	}
	if(!title && node.id) {
		var lenPrefix = store.idPrefix.length;
		if(node.id.substr(0,lenPrefix) == store.idPrefix)
			title = node.id.substr(lenPrefix);
	}
	return title;
};

TW21Loader.prototype.internalizeTiddler = function(store,tiddler,title,node)
{
	var e = node.firstChild;
	var text = null;
	if(node.getAttribute("tiddler")) {
		text = getNodeText(e).unescapeLineBreaks();
	} else {
		while(e.nodeName!="PRE" && e.nodeName!="pre") {
			e = e.nextSibling;
		}
		text = e.innerHTML.replace(/\r/mg,"").htmlDecode();
	}
	var creator = node.getAttribute("creator");
	var modifier = node.getAttribute("modifier");
	var c = node.getAttribute("created");
	var m = node.getAttribute("modified");
	var created = c ? Date.convertFromYYYYMMDDHHMMSS(c) : version.date;
	var modified = m ? Date.convertFromYYYYMMDDHHMMSS(m) : created;
	var tags = node.getAttribute("tags");
	var fields = {};
	var attrs = node.attributes;
	for(var i = attrs.length-1; i >= 0; i--) {
		var name = attrs[i].name;
		if(attrs[i].specified && !TiddlyWiki.isStandardField(name)) {
			fields[name] = attrs[i].value.unescapeLineBreaks();
		}
	}
	tiddler.assign(title,text,modifier,modified,tags,created,fields,creator);
	return tiddler;
};

//--
//-- TW21Saver (inherits from SaverBase)
//--

function TW21Saver() {}

TW21Saver.prototype = new SaverBase();

TW21Saver.prototype.externalizeTiddler = function(store,tiddler)
{
	try {
		var extendedAttributes = "";
		var usePre = config.options.chkUsePreForStorage;
		store.forEachField(tiddler,
			function(tiddler,fieldName,value) {
				// don't store stuff from the temp namespace
				if(typeof value != "string")
					value = "";
				if(!fieldName.match(/^temp\./))
					extendedAttributes += ' %0="%1"'.format([fieldName,value.escapeLineBreaks().htmlEncode()]);
			},true);
		var created = tiddler.created;
		var modified = tiddler.modified;
		var attributes = tiddler.creator ? ' creator="' + tiddler.creator.htmlEncode() + '"' : "";
		attributes += tiddler.modifier ? ' modifier="' + tiddler.modifier.htmlEncode() + '"' : "";
		attributes += (usePre && created == version.date) ? "" :' created="' + created.convertToYYYYMMDDHHMM() + '"';
		attributes += (usePre && modified == created) ? "" : ' modified="' + modified.convertToYYYYMMDDHHMM() +'"';
		var tags = tiddler.getTags();
		if(!usePre || tags)
			attributes += ' tags="' + tags.htmlEncode() + '"';
		return ('<div %0="%1"%2%3>%4</'+'div>').format([
				usePre ? "title" : "tiddler",
				tiddler.title.htmlEncode(),
				attributes,
				extendedAttributes,
				usePre ? "\n<pre>" + tiddler.text.htmlEncode() + "</pre>\n" : tiddler.text.escapeLineBreaks().htmlEncode()
			]);
	} catch (ex) {
		throw exceptionText(ex,config.messages.tiddlerSaveError.format([tiddler.title]));
	}
};

//]]>
</script>
<script id="jsdeprecatedArea" type="text/javascript">
//<![CDATA[
//--
//-- Deprecated Crypto functions and associated conversion routines.
//-- Use the jQuery.encoding functions directly instead.
//--

// Crypto 'namespace'
function Crypto() {}

// Convert a string to an array of big-endian 32-bit words
Crypto.strToBe32s = function(str)
{
	return jQuery.encoding.strToBe32s(str);
};

// Convert an array of big-endian 32-bit words to a string
Crypto.be32sToStr = function(be)
{
	return jQuery.encoding.be32sToStr(be);
};

// Convert an array of big-endian 32-bit words to a hex string
Crypto.be32sToHex = function(be)
{
	return jQuery.encoding.be32sToHex(be);
};

// Return, in hex, the SHA-1 hash of a string
Crypto.hexSha1Str = function(str)
{
	return jQuery.encoding.digests.hexSha1Str(str);
};

// Return the SHA-1 hash of a string
Crypto.sha1Str = function(str)
{
	return jQuery.encoding.digests.sha1Str(str);
};

// Calculate the SHA-1 hash of an array of blen bytes of big-endian 32-bit words
Crypto.sha1 = function(x,blen)
{
	return jQuery.encoding.digests.sha1(x,blen);
};

//--
//-- Deprecated DOM utilities
//--

// @Deprecated: Use jQuery.stylesheet instead
function setStylesheet(s,id,doc)
{
	jQuery.twStylesheet(s,{ id: id, doc: doc });
}

// @Deprecated: Use jQuery.stylesheet.remove instead
function removeStyleSheet(id)
{
	jQuery.twStylesheet.remove({ id: id });
}
//--
//-- Deprecated HTTP request code
//-- Use the jQuery ajax functions directly instead
//--

function loadRemoteFile(url,callback,params)
{
	return httpReq("GET",url,callback,params);
}

function doHttp(type,url,data,contentType,username,password,callback,params,headers,allowCache)
{
	return httpReq(type,url,callback,params,headers,data,contentType,username,password,allowCache);
}

function httpReq(type,url,callback,params,headers,data,contentType,username,password,allowCache)
{
	var options = {
		type:type,
		url:url,
		processData:false,
		data:data,
		cache:!!allowCache,
		beforeSend: function(xhr) {
			for(var i in headers)
				xhr.setRequestHeader(i,headers[i]);
			xhr.setRequestHeader("X-Requested-With", "TiddlyWiki " + formatVersion());
		}
	};

	if(callback) {
		options.complete = function(xhr,textStatus) {
			if(jQuery.httpSuccess(xhr))
				callback(true,params,xhr.responseText,url,xhr);
			else
				callback(false,params,null,url,xhr);
		};
	}
	if(contentType)
		options.contentType = contentType;
	if(username)
		options.username = username;
	if(password)
		options.password = password;
	if(window.Components && window.netscape && window.netscape.security && document.location.protocol.indexOf("http") == -1)
		window.netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	return jQuery.ajax(options);
}

//--
//-- Deprecated String functions
//--

// @Deprecated: no direct replacement, since not used in core code
String.prototype.toJSONString = function()
{
	// Convert a string to it's JSON representation by encoding control characters, double quotes and backslash. See json.org
	var m = {
		'\b': '\\b',
		'\f': '\\f',
		'\n': '\\n',
		'\r': '\\r',
		'\t': '\\t',
		'"' : '\\"',
		'\\': '\\\\'
		};
	var replaceFn = function(a,b) {
		var c = m[b];
		if(c)
			return c;
		c = b.charCodeAt();
		return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
		};
	if(/["\\\x00-\x1f]/.test(this))
		return '"' + this.replace(/([\x00-\x1f\\"])/g,replaceFn) + '"';
	return '"' + this + '"';
};

//--
//-- Deprecated Tiddler code
//--

// @Deprecated: Use tiddlerToRssItem(tiddler,uri) instead
Tiddler.prototype.toRssItem = function(uri)
{
	return tiddlerToRssItem(this,uri);
};

// @Deprecated: Use "<item>\n" + tiddlerToRssItem(tiddler,uri)  + "\n</item>" instead
Tiddler.prototype.saveToRss = function(uri)
{
	return "<item>\n" + tiddlerToRssItem(this,uri) + "\n</item>";
};

// @Deprecated: Use jQuery.encoding.digests.hexSha1Str instead
Tiddler.prototype.generateFingerprint = function()
{
	return "0x" + Crypto.hexSha1Str(this.text);
};

//]]>
</script>
<script id="jslibArea" type="text/javascript">
//<![CDATA[
/*!
 * jQuery JavaScript Library v1.4.3
 * http://jquery.com/
 *
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2010, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Thu Oct 14 23:10:06 2010 -0400
 */
(function(E,A){function U(){return false}function ba(){return true}function ja(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ga(a){var b,d,e=[],f=[],h,k,l,n,s,v,B,D;k=c.data(this,this.nodeType?"events":"__events__");if(typeof k==="function")k=k.events;if(!(a.liveFired===this||!k||!k.live||a.button&&a.type==="click")){if(a.namespace)D=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var H=k.live.slice(0);for(n=0;n<H.length;n++){k=H[n];k.origType.replace(X,
"")===a.type?f.push(k.selector):H.splice(n--,1)}f=c(a.target).closest(f,a.currentTarget);s=0;for(v=f.length;s<v;s++){B=f[s];for(n=0;n<H.length;n++){k=H[n];if(B.selector===k.selector&&(!D||D.test(k.namespace))){l=B.elem;h=null;if(k.preType==="mouseenter"||k.preType==="mouseleave"){a.type=k.preType;h=c(a.relatedTarget).closest(k.selector)[0]}if(!h||h!==l)e.push({elem:l,handleObj:k,level:B.level})}}}s=0;for(v=e.length;s<v;s++){f=e[s];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;
a.handleObj=f.handleObj;D=f.handleObj.origHandler.apply(f.elem,arguments);if(D===false||a.isPropagationStopped()){d=f.level;if(D===false)b=false}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(Ha,"`").replace(Ia,"&")}function ka(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Ja.test(b))return c.filter(b,
e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function la(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this,e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var k in e[h])c.event.add(this,h,e[h][k],e[h][k].data)}}})}function Ka(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}
function ma(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?La:Ma,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a,"margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function ca(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Na.test(a)?e(a,h):ca(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?
e(a,""):c.each(b,function(f,h){ca(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(na.concat.apply([],na.slice(0,b)),function(){d[this]=a});return d}function oa(a){if(!da[a]){var b=c("<"+a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";da[a]=d}return da[a]}function ea(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var u=E.document,c=function(){function a(){if(!b.isReady){try{u.documentElement.doScroll("left")}catch(i){setTimeout(a,
1);return}b.ready()}}var b=function(i,r){return new b.fn.init(i,r)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,k=/\S/,l=/^\s+/,n=/\s+$/,s=/\W/,v=/\d/,B=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,D=/^[\],:{}\s]*$/,H=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,G=/(?:^|:|,)(?:\s*\[)+/g,M=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,j=/(msie) ([\w.]+)/,o=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,
q=[],t,x=Object.prototype.toString,C=Object.prototype.hasOwnProperty,P=Array.prototype.push,N=Array.prototype.slice,R=String.prototype.trim,Q=Array.prototype.indexOf,L={};b.fn=b.prototype={init:function(i,r){var y,z,F;if(!i)return this;if(i.nodeType){this.context=this[0]=i;this.length=1;return this}if(i==="body"&&!r&&u.body){this.context=u;this[0]=u.body;this.selector="body";this.length=1;return this}if(typeof i==="string")if((y=h.exec(i))&&(y[1]||!r))if(y[1]){F=r?r.ownerDocument||r:u;if(z=B.exec(i))if(b.isPlainObject(r)){i=
[u.createElement(z[1])];b.fn.attr.call(i,r,true)}else i=[F.createElement(z[1])];else{z=b.buildFragment([y[1]],[F]);i=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this,i)}else{if((z=u.getElementById(y[2]))&&z.parentNode){if(z.id!==y[2])return f.find(i);this.length=1;this[0]=z}this.context=u;this.selector=i;return this}else if(!r&&!s.test(i)){this.selector=i;this.context=u;i=u.getElementsByTagName(i);return b.merge(this,i)}else return!r||r.jquery?(r||f).find(i):b(r).find(i);
else if(b.isFunction(i))return f.ready(i);if(i.selector!==A){this.selector=i.selector;this.context=i.context}return b.makeArray(i,this)},selector:"",jquery:"1.4.3",length:0,size:function(){return this.length},toArray:function(){return N.call(this,0)},get:function(i){return i==null?this.toArray():i<0?this.slice(i)[0]:this[i]},pushStack:function(i,r,y){var z=b();b.isArray(i)?P.apply(z,i):b.merge(z,i);z.prevObject=this;z.context=this.context;if(r==="find")z.selector=this.selector+(this.selector?" ":
"")+y;else if(r)z.selector=this.selector+"."+r+"("+y+")";return z},each:function(i,r){return b.each(this,i,r)},ready:function(i){b.bindReady();if(b.isReady)i.call(u,b);else q&&q.push(i);return this},eq:function(i){return i===-1?this.slice(i):this.slice(i,+i+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(i){return this.pushStack(b.map(this,function(r,y){return i.call(r,
y,r)}))},end:function(){return this.prevObject||b(null)},push:P,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var i=arguments[0]||{},r=1,y=arguments.length,z=false,F,I,K,J,fa;if(typeof i==="boolean"){z=i;i=arguments[1]||{};r=2}if(typeof i!=="object"&&!b.isFunction(i))i={};if(y===r){i=this;--r}for(;r<y;r++)if((F=arguments[r])!=null)for(I in F){K=i[I];J=F[I];if(i!==J)if(z&&J&&(b.isPlainObject(J)||(fa=b.isArray(J)))){if(fa){fa=false;clone=K&&b.isArray(K)?K:[]}else clone=
K&&b.isPlainObject(K)?K:{};i[I]=b.extend(z,clone,J)}else if(J!==A)i[I]=J}return i};b.extend({noConflict:function(i){E.$=e;if(i)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(i){i===true&&b.readyWait--;if(!b.readyWait||i!==true&&!b.isReady){if(!u.body)return setTimeout(b.ready,1);b.isReady=true;if(!(i!==true&&--b.readyWait>0)){if(q){for(var r=0;i=q[r++];)i.call(u,b);q=null}b.fn.triggerHandler&&b(u).triggerHandler("ready")}}},bindReady:function(){if(!p){p=true;if(u.readyState==="complete")return setTimeout(b.ready,
1);if(u.addEventListener){u.addEventListener("DOMContentLoaded",t,false);E.addEventListener("load",b.ready,false)}else if(u.attachEvent){u.attachEvent("onreadystatechange",t);E.attachEvent("onload",b.ready);var i=false;try{i=E.frameElement==null}catch(r){}u.documentElement.doScroll&&i&&a()}}},isFunction:function(i){return b.type(i)==="function"},isArray:Array.isArray||function(i){return b.type(i)==="array"},isWindow:function(i){return i&&typeof i==="object"&&"setInterval"in i},isNaN:function(i){return i==
null||!v.test(i)||isNaN(i)},type:function(i){return i==null?String(i):L[x.call(i)]||"object"},isPlainObject:function(i){if(!i||b.type(i)!=="object"||i.nodeType||b.isWindow(i))return false;if(i.constructor&&!C.call(i,"constructor")&&!C.call(i.constructor.prototype,"isPrototypeOf"))return false;for(var r in i);return r===A||C.call(i,r)},isEmptyObject:function(i){for(var r in i)return false;return true},error:function(i){throw i;},parseJSON:function(i){if(typeof i!=="string"||!i)return null;i=b.trim(i);
if(D.test(i.replace(H,"@").replace(w,"]").replace(G,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(i):(new Function("return "+i))();else b.error("Invalid JSON: "+i)},noop:function(){},globalEval:function(i){if(i&&k.test(i)){var r=u.getElementsByTagName("head")[0]||u.documentElement,y=u.createElement("script");y.type="text/javascript";if(b.support.scriptEval)y.appendChild(u.createTextNode(i));else y.text=i;r.insertBefore(y,r.firstChild);r.removeChild(y)}},nodeName:function(i,r){return i.nodeName&&i.nodeName.toUpperCase()===
r.toUpperCase()},each:function(i,r,y){var z,F=0,I=i.length,K=I===A||b.isFunction(i);if(y)if(K)for(z in i){if(r.apply(i[z],y)===false)break}else for(;F<I;){if(r.apply(i[F++],y)===false)break}else if(K)for(z in i){if(r.call(i[z],z,i[z])===false)break}else for(y=i[0];F<I&&r.call(y,F,y)!==false;y=i[++F]);return i},trim:R?function(i){return i==null?"":R.call(i)}:function(i){return i==null?"":i.toString().replace(l,"").replace(n,"")},makeArray:function(i,r){var y=r||[];if(i!=null){var z=b.type(i);i.length==
null||z==="string"||z==="function"||z==="regexp"||b.isWindow(i)?P.call(y,i):b.merge(y,i)}return y},inArray:function(i,r){if(r.indexOf)return r.indexOf(i);for(var y=0,z=r.length;y<z;y++)if(r[y]===i)return y;return-1},merge:function(i,r){var y=i.length,z=0;if(typeof r.length==="number")for(var F=r.length;z<F;z++)i[y++]=r[z];else for(;r[z]!==A;)i[y++]=r[z++];i.length=y;return i},grep:function(i,r,y){var z=[],F;y=!!y;for(var I=0,K=i.length;I<K;I++){F=!!r(i[I],I);y!==F&&z.push(i[I])}return z},map:function(i,
r,y){for(var z=[],F,I=0,K=i.length;I<K;I++){F=r(i[I],I,y);if(F!=null)z[z.length]=F}return z.concat.apply([],z)},guid:1,proxy:function(i,r,y){if(arguments.length===2)if(typeof r==="string"){y=i;i=y[r];r=A}else if(r&&!b.isFunction(r)){y=r;r=A}if(!r&&i)r=function(){return i.apply(y||this,arguments)};if(i)r.guid=i.guid=i.guid||r.guid||b.guid++;return r},access:function(i,r,y,z,F,I){var K=i.length;if(typeof r==="object"){for(var J in r)b.access(i,J,r[J],z,F,y);return i}if(y!==A){z=!I&&z&&b.isFunction(y);
for(J=0;J<K;J++)F(i[J],r,z?y.call(i[J],J,F(i[J],r)):y,I);return i}return K?F(i[0],r):A},now:function(){return(new Date).getTime()},uaMatch:function(i){i=i.toLowerCase();i=M.exec(i)||g.exec(i)||j.exec(i)||i.indexOf("compatible")<0&&o.exec(i)||[];return{browser:i[1]||"",version:i[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(i,r){L["[object "+r+"]"]=r.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=
m.version}if(b.browser.webkit)b.browser.safari=true;if(Q)b.inArray=function(i,r){return Q.call(r,i)};if(!/\s/.test("\u00a0")){l=/^[\s\xA0]+/;n=/[\s\xA0]+$/}f=b(u);if(u.addEventListener)t=function(){u.removeEventListener("DOMContentLoaded",t,false);b.ready()};else if(u.attachEvent)t=function(){if(u.readyState==="complete"){u.detachEvent("onreadystatechange",t);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=u.documentElement,b=u.createElement("script"),d=u.createElement("div"),
e="script"+c.now();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],k=u.createElement("select"),l=k.appendChild(u.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),
hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:l.selected,optDisabled:false,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};k.disabled=true;c.support.optDisabled=!l.disabled;b.type="text/javascript";try{b.appendChild(u.createTextNode("window."+e+"=1;"))}catch(n){}a.insertBefore(b,
a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function s(){c.support.noCloneEvent=false;d.detachEvent("onclick",s)});d.cloneNode(true).fireEvent("onclick")}d=u.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=u.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var s=u.createElement("div");
s.style.width=s.style.paddingLeft="1px";u.body.appendChild(s);c.boxModel=c.support.boxModel=s.offsetWidth===2;if("zoom"in s.style){s.style.display="inline";s.style.zoom=1;c.support.inlineBlockNeedsLayout=s.offsetWidth===2;s.style.display="";s.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=s.offsetWidth!==2}s.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var v=s.getElementsByTagName("td");c.support.reliableHiddenOffsets=v[0].offsetHeight===
0;v[0].style.display="";v[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&v[0].offsetHeight===0;s.innerHTML="";u.body.removeChild(s).style.display="none"});a=function(s){var v=u.createElement("div");s="on"+s;var B=s in v;if(!B){v.setAttribute(s,"return;");B=typeof v[s]==="function"}return B};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",
cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var pa={},Oa=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?pa:a;var e=a.nodeType,f=e?a[c.expando]:null,h=c.cache;if(!(e&&!f&&typeof b==="string"&&d===A)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=
c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==A)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?pa:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando);else if(d)delete f[e];else for(var k in a)delete a[k]}},acceptData:function(a){if(a.nodeName){var b=
c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){if(typeof a==="undefined")return this.length?c.data(this[0]):null;else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===A){var e=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(e===A&&this.length){e=c.data(this[0],a);if(e===A&&this[0].nodeType===1){e=this[0].getAttribute("data-"+a);if(typeof e===
"string")try{e=e==="true"?true:e==="false"?false:e==="null"?null:!c.isNaN(e)?parseFloat(e):Oa.test(e)?c.parseJSON(e):e}catch(f){}else e=A}}return e===A&&d[1]?this.data(d[0]):e}else return this.each(function(){var h=c(this),k=[d[0],b];h.triggerHandler("setData"+d[1]+"!",k);c.data(this,a,b);h.triggerHandler("changeData"+d[1]+"!",k)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e=c.data(a,b);if(!d)return e||
[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===A)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,
a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var qa=/[\n\t]/g,ga=/\s+/,Pa=/\r/g,Qa=/^(?:href|src|style)$/,Ra=/^(?:button|input)$/i,Sa=/^(?:button|input|object|select|textarea)$/i,Ta=/^a(?:rea)?$/i,ra=/^(?:radio|checkbox)$/i;c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,
a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(s){var v=c(this);v.addClass(a.call(this,s,v.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ga),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1)if(f.className){for(var h=" "+f.className+" ",k=f.className,l=0,n=b.length;l<n;l++)if(h.indexOf(" "+b[l]+" ")<0)k+=" "+b[l];f.className=c.trim(k)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(n){var s=
c(this);s.removeClass(a.call(this,n,s.attr("class")))});if(a&&typeof a==="string"||a===A)for(var b=(a||"").split(ga),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(qa," "),k=0,l=b.length;k<l;k++)h=h.replace(" "+b[k]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,
f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,k=c(this),l=b,n=a.split(ga);f=n[h++];){l=e?l:!k.hasClass(f);k[l?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(qa," ").indexOf(a)>-1)return true;return false},
val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one";if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var k=f[h];if(k.selected&&(c.support.optDisabled?!k.disabled:k.getAttribute("disabled")===null)&&(!k.parentNode.disabled||!c.nodeName(k.parentNode,"optgroup"))){a=c(k).val();if(b)return a;d.push(a)}}return d}if(ra.test(b.type)&&
!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Pa,"")}return A}var l=c.isFunction(a);return this.each(function(n){var s=c(this),v=a;if(this.nodeType===1){if(l)v=a.call(this,n,s.val());if(v==null)v="";else if(typeof v==="number")v+="";else if(c.isArray(v))v=c.map(v,function(D){return D==null?"":D+""});if(c.isArray(v)&&ra.test(this.type))this.checked=c.inArray(s.val(),v)>=0;else if(c.nodeName(this,"select")){var B=c.makeArray(v);c("option",this).each(function(){this.selected=
c.inArray(c(this).val(),B)>=0});if(!B.length)this.selectedIndex=-1}else this.value=v}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return A;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==A;b=e&&c.props[b]||b;if(a.nodeType===1){var h=Qa.test(b);if((b in a||a[b]!==A)&&e&&!h){if(f){b==="type"&&Ra.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:Sa.test(a.nodeName)||Ta.test(a.nodeName)&&a.href?0:A;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return A;a=!c.support.hrefNormalized&&e&&
h?a.getAttribute(b,2):a.getAttribute(b);return a===null?A:a}}});var X=/\.(.*)$/,ha=/^(?:textarea|input|select)$/i,Ha=/\./g,Ia=/ /g,Ua=/[^\w\s.|`]/g,Va=function(a){return a.replace(Ua,"\\$&")},sa={focusin:0,focusout:0};c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var k=a.nodeType?"events":"__events__",l=h[k],n=h.handle;if(typeof l===
"function"){n=l.handle;l=l.events}else if(!l){a.nodeType||(h[k]=h=function(){});h.events=l={}}if(!n)h.handle=n=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(n.elem,arguments):A};n.elem=a;b=b.split(" ");for(var s=0,v;k=b[s++];){h=f?c.extend({},f):{handler:d,data:e};if(k.indexOf(".")>-1){v=k.split(".");k=v.shift();h.namespace=v.slice(0).sort().join(".")}else{v=[];h.namespace=""}h.type=k;if(!h.guid)h.guid=d.guid;var B=l[k],D=c.event.special[k]||{};if(!B){B=l[k]=[];
if(!D.setup||D.setup.call(a,e,v,n)===false)if(a.addEventListener)a.addEventListener(k,n,false);else a.attachEvent&&a.attachEvent("on"+k,n)}if(D.add){D.add.call(a,h);if(!h.handler.guid)h.handler.guid=d.guid}B.push(h);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,k=0,l,n,s,v,B,D,H=a.nodeType?"events":"__events__",w=c.data(a),G=w&&w[H];if(w&&G){if(typeof G==="function"){w=G;G=G.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||
typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in G)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[k++];){v=f;l=f.indexOf(".")<0;n=[];if(!l){n=f.split(".");f=n.shift();s=RegExp("(^|\\.)"+c.map(n.slice(0).sort(),Va).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(B=G[f])if(d){v=c.event.special[f]||{};for(h=e||0;h<B.length;h++){D=B[h];if(d.guid===D.guid){if(l||s.test(D.namespace)){e==null&&B.splice(h--,1);v.remove&&v.remove.call(a,D)}if(e!=null)break}}if(B.length===0||e!=null&&B.length===1){if(!v.teardown||
v.teardown.call(a,n)===false)c.removeEvent(a,f,w.handle);delete G[f]}}else for(h=0;h<B.length;h++){D=B[h];if(l||s.test(D.namespace)){c.event.remove(a,v,D.handler,h);B.splice(h--,1)}}}if(c.isEmptyObject(G)){if(b=w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,H);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=
f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return A;a.result=A;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===
false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){e=a.target;var k,l=f.replace(X,""),n=c.nodeName(e,"a")&&l==="click",s=c.event.special[l]||{};if((!s._default||s._default.call(d,a)===false)&&!n&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[l]){if(k=e["on"+l])e["on"+l]=null;c.event.triggered=true;e[l]()}}catch(v){}if(k)e["on"+l]=k;c.event.triggered=false}}},handle:function(a){var b,d,e;
d=[];var f,h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var k=d.length;f<k;f++){var l=d[f];if(b||e.test(l.namespace)){a.handler=l.handler;a.data=
l.data;a.handleObj=l;l=l.handler.apply(this,h);if(l!==A){a.result=l;if(l===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||u;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=u.documentElement;d=u.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==A)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ga,guid:a.handler.guid}))},remove:function(a){c.event.remove(this,
Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=u.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=
c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ba;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ba;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ba;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U};
var ta=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},ua=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?ua:ta,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?ua:ta)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!==
"form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=A;return ja("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=A;return ja("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V,
va=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ha.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=va(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===A||f===e))if(e!=null||f){a.type="change";a.liveFired=
A;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",va(a))}},setup:function(){if(this.type===
"file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ha.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ha.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}u.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){sa[b]++===0&&u.addEventListener(a,d,true)},teardown:function(){--sa[b]===
0&&u.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=A}var k=b==="one"?c.proxy(f,function(n){c(this).unbind(n,k);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var l=this.length;h<l;h++)c.event.add(this[h],d,k,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d,
a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d=
1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var wa={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var k,l=0,n,s,v=h||this.selector;h=h?this:c(this.context);if(typeof d===
"object"&&!d.preventDefault){for(k in d)h[b](k,e,d[k],v);return this}if(c.isFunction(e)){f=e;e=A}for(d=(d||"").split(" ");(k=d[l++])!=null;){n=X.exec(k);s="";if(n){s=n[0];k=k.replace(X,"")}if(k==="hover")d.push("mouseenter"+s,"mouseleave"+s);else{n=k;if(k==="focus"||k==="blur"){d.push(wa[k]+s);k+=s}else k=(wa[k]||k)+s;if(b==="live"){s=0;for(var B=h.length;s<B;s++)c.event.add(h[s],"live."+Y(k,v),{data:e,selector:v,handler:f,origType:k,origHandler:f,preType:n})}else h.unbind("live."+Y(k,v),f)}}return this}});
c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});
(function(){function a(g,j,o,m,p,q){p=0;for(var t=m.length;p<t;p++){var x=m[p];if(x){x=x[g];for(var C=false;x;){if(x.sizcache===o){C=m[x.sizset];break}if(x.nodeType===1&&!q){x.sizcache=o;x.sizset=p}if(x.nodeName.toLowerCase()===j){C=x;break}x=x[g]}m[p]=C}}}function b(g,j,o,m,p,q){p=0;for(var t=m.length;p<t;p++){var x=m[p];if(x){x=x[g];for(var C=false;x;){if(x.sizcache===o){C=m[x.sizset];break}if(x.nodeType===1){if(!q){x.sizcache=o;x.sizset=p}if(typeof j!=="string"){if(x===j){C=true;break}}else if(l.filter(j,
[x]).length>0){C=x;break}}x=x[g]}m[p]=C}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,k=true;[0,0].sort(function(){k=false;return 0});var l=function(g,j,o,m){o=o||[];var p=j=j||u;if(j.nodeType!==1&&j.nodeType!==9)return[];if(!g||typeof g!=="string")return o;var q=[],t,x,C,P,N=true,R=l.isXML(j),Q=g,L;do{d.exec("");if(t=d.exec(Q)){Q=t[3];q.push(t[1]);if(t[2]){P=t[3];
break}}}while(t);if(q.length>1&&s.exec(g))if(q.length===2&&n.relative[q[0]])x=M(q[0]+q[1],j);else for(x=n.relative[q[0]]?[j]:l(q.shift(),j);q.length;){g=q.shift();if(n.relative[g])g+=q.shift();x=M(g,x)}else{if(!m&&q.length>1&&j.nodeType===9&&!R&&n.match.ID.test(q[0])&&!n.match.ID.test(q[q.length-1])){t=l.find(q.shift(),j,R);j=t.expr?l.filter(t.expr,t.set)[0]:t.set[0]}if(j){t=m?{expr:q.pop(),set:D(m)}:l.find(q.pop(),q.length===1&&(q[0]==="~"||q[0]==="+")&&j.parentNode?j.parentNode:j,R);x=t.expr?l.filter(t.expr,
t.set):t.set;if(q.length>0)C=D(x);else N=false;for(;q.length;){t=L=q.pop();if(n.relative[L])t=q.pop();else L="";if(t==null)t=j;n.relative[L](C,t,R)}}else C=[]}C||(C=x);C||l.error(L||g);if(f.call(C)==="[object Array]")if(N)if(j&&j.nodeType===1)for(g=0;C[g]!=null;g++){if(C[g]&&(C[g]===true||C[g].nodeType===1&&l.contains(j,C[g])))o.push(x[g])}else for(g=0;C[g]!=null;g++)C[g]&&C[g].nodeType===1&&o.push(x[g]);else o.push.apply(o,C);else D(C,o);if(P){l(P,p,o,m);l.uniqueSort(o)}return o};l.uniqueSort=function(g){if(w){h=
k;g.sort(w);if(h)for(var j=1;j<g.length;j++)g[j]===g[j-1]&&g.splice(j--,1)}return g};l.matches=function(g,j){return l(g,null,null,j)};l.matchesSelector=function(g,j){return l(j,null,null,[g]).length>0};l.find=function(g,j,o){var m;if(!g)return[];for(var p=0,q=n.order.length;p<q;p++){var t=n.order[p],x;if(x=n.leftMatch[t].exec(g)){var C=x[1];x.splice(1,1);if(C.substr(C.length-1)!=="\\"){x[1]=(x[1]||"").replace(/\\/g,"");m=n.find[t](x,j,o);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=j.getElementsByTagName("*"));
return{set:m,expr:g}};l.filter=function(g,j,o,m){for(var p=g,q=[],t=j,x,C,P=j&&j[0]&&l.isXML(j[0]);g&&j.length;){for(var N in n.filter)if((x=n.leftMatch[N].exec(g))!=null&&x[2]){var R=n.filter[N],Q,L;L=x[1];C=false;x.splice(1,1);if(L.substr(L.length-1)!=="\\"){if(t===q)q=[];if(n.preFilter[N])if(x=n.preFilter[N](x,t,o,q,m,P)){if(x===true)continue}else C=Q=true;if(x)for(var i=0;(L=t[i])!=null;i++)if(L){Q=R(L,x,i,t);var r=m^!!Q;if(o&&Q!=null)if(r)C=true;else t[i]=false;else if(r){q.push(L);C=true}}if(Q!==
A){o||(t=q);g=g.replace(n.match[N],"");if(!C)return[];break}}}if(g===p)if(C==null)l.error(g);else break;p=g}return t};l.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=l.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,j){var o=typeof j==="string",m=o&&!/\W/.test(j);o=o&&!m;if(m)j=j.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=o||q&&q.nodeName.toLowerCase()===
j?q||false:q===j}o&&l.filter(j,g,true)},">":function(g,j){var o=typeof j==="string",m,p=0,q=g.length;if(o&&!/\W/.test(j))for(j=j.toLowerCase();p<q;p++){if(m=g[p]){o=m.parentNode;g[p]=o.nodeName.toLowerCase()===j?o:false}}else{for(;p<q;p++)if(m=g[p])g[p]=o?m.parentNode:m.parentNode===j;o&&l.filter(j,g,true)}},"":function(g,j,o){var m=e++,p=b,q;if(typeof j==="string"&&!/\W/.test(j)){q=j=j.toLowerCase();p=a}p("parentNode",j,m,g,q,o)},"~":function(g,j,o){var m=e++,p=b,q;if(typeof j==="string"&&!/\W/.test(j)){q=
j=j.toLowerCase();p=a}p("previousSibling",j,m,g,q,o)}},find:{ID:function(g,j,o){if(typeof j.getElementById!=="undefined"&&!o)return(g=j.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,j){if(typeof j.getElementsByName!=="undefined"){for(var o=[],m=j.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&o.push(m[p]);return o.length===0?null:o}},TAG:function(g,j){return j.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,j,o,m,p,q){g=" "+g[1].replace(/\\/g,
"")+" ";if(q)return g;q=0;for(var t;(t=j[q])!=null;q++)if(t)if(p^(t.className&&(" "+t.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))o||m.push(t);else if(o)j[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var j=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=j[1]+(j[2]||1)-0;g[3]=j[3]-0}g[0]=e++;return g},ATTR:function(g,j,o,
m,p,q){j=g[1].replace(/\\/g,"");if(!q&&n.attrMap[j])g[1]=n.attrMap[j];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,j,o,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=l(g[3],null,null,j);else{g=l.filter(g[3],j,o,true^p);o||m.push.apply(m,g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===
true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,j,o){return!!l(o[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===
g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,j){return j===0},last:function(g,j,o,m){return j===m.length-1},even:function(g,j){return j%2===0},odd:function(g,j){return j%2===1},lt:function(g,j,o){return j<o[3]-0},gt:function(g,j,o){return j>o[3]-0},nth:function(g,j,o){return o[3]-
0===j},eq:function(g,j,o){return o[3]-0===j}},filter:{PSEUDO:function(g,j,o,m){var p=j[1],q=n.filters[p];if(q)return q(g,o,j,m);else if(p==="contains")return(g.textContent||g.innerText||l.getText([g])||"").indexOf(j[3])>=0;else if(p==="not"){j=j[3];o=0;for(m=j.length;o<m;o++)if(j[o]===g)return false;return true}else l.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,j){var o=j[1],m=g;switch(o){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(o===
"first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":o=j[2];var p=j[3];if(o===1&&p===0)return true;var q=j[0],t=g.parentNode;if(t&&(t.sizcache!==q||!g.nodeIndex)){var x=0;for(m=t.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++x;t.sizcache=q}m=g.nodeIndex-p;return o===0?m===0:m%o===0&&m/o>=0}},ID:function(g,j){return g.nodeType===1&&g.getAttribute("id")===j},TAG:function(g,j){return j==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===
j},CLASS:function(g,j){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(j)>-1},ATTR:function(g,j){var o=j[1];o=n.attrHandle[o]?n.attrHandle[o](g):g[o]!=null?g[o]:g.getAttribute(o);var m=o+"",p=j[2],q=j[4];return o==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&o!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,j,o,m){var p=n.setFilters[j[2]];
if(p)return p(g,o,j,m)}}},s=n.match.POS,v=function(g,j){return"\\"+(j-0+1)},B;for(B in n.match){n.match[B]=RegExp(n.match[B].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[B]=RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[B].source.replace(/\\(\d+)/g,v))}var D=function(g,j){g=Array.prototype.slice.call(g,0);if(j){j.push.apply(j,g);return j}return g};try{Array.prototype.slice.call(u.documentElement.childNodes,0)}catch(H){D=function(g,j){var o=j||[],m=0;if(f.call(g)==="[object Array]")Array.prototype.push.apply(o,
g);else if(typeof g.length==="number")for(var p=g.length;m<p;m++)o.push(g[m]);else for(;g[m];m++)o.push(g[m]);return o}}var w,G;if(u.documentElement.compareDocumentPosition)w=function(g,j){if(g===j){h=true;return 0}if(!g.compareDocumentPosition||!j.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(j)&4?-1:1};else{w=function(g,j){var o=[],m=[],p=g.parentNode,q=j.parentNode,t=p;if(g===j){h=true;return 0}else if(p===q)return G(g,j);else if(p){if(!q)return 1}else return-1;
for(;t;){o.unshift(t);t=t.parentNode}for(t=q;t;){m.unshift(t);t=t.parentNode}p=o.length;q=m.length;for(t=0;t<p&&t<q;t++)if(o[t]!==m[t])return G(o[t],m[t]);return t===p?G(g,m[t],-1):G(o[t],j,1)};G=function(g,j,o){if(g===j)return o;for(g=g.nextSibling;g;){if(g===j)return-1;g=g.nextSibling}return 1}}l.getText=function(g){for(var j="",o,m=0;g[m];m++){o=g[m];if(o.nodeType===3||o.nodeType===4)j+=o.nodeValue;else if(o.nodeType!==8)j+=l.getText(o.childNodes)}return j};(function(){var g=u.createElement("div"),
j="script"+(new Date).getTime();g.innerHTML="<a name='"+j+"'/>";var o=u.documentElement;o.insertBefore(g,o.firstChild);if(u.getElementById(j)){n.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:A:[]};n.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}o.removeChild(g);
o=g=null})();(function(){var g=u.createElement("div");g.appendChild(u.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(j,o){var m=o.getElementsByTagName(j[1]);if(j[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(j){return j.getAttribute("href",2)};g=null})();u.querySelectorAll&&
function(){var g=l,j=u.createElement("div");j.innerHTML="<p class='TEST'></p>";if(!(j.querySelectorAll&&j.querySelectorAll(".TEST").length===0)){l=function(m,p,q,t){p=p||u;if(!t&&!l.isXML(p))if(p.nodeType===9)try{return D(p.querySelectorAll(m),q)}catch(x){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var C=p.id,P=p.id="__sizzle__";try{return D(p.querySelectorAll("#"+P+" "+m),q)}catch(N){}finally{if(C)p.id=C;else p.removeAttribute("id")}}return g(m,p,q,t)};for(var o in g)l[o]=g[o];
j=null}}();(function(){var g=u.documentElement,j=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,o=false;try{j.call(u.documentElement,":sizzle")}catch(m){o=true}if(j)l.matchesSelector=function(p,q){try{if(o||!n.match.PSEUDO.test(q))return j.call(p,q)}catch(t){}return l(q,null,null,[p]).length>0}})();(function(){var g=u.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===
0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(j,o,m){if(typeof o.getElementsByClassName!=="undefined"&&!m)return o.getElementsByClassName(j[1])};g=null}}})();l.contains=u.documentElement.contains?function(g,j){return g!==j&&(g.contains?g.contains(j):true)}:function(g,j){return!!(g.compareDocumentPosition(j)&16)};l.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var M=function(g,
j){for(var o=[],m="",p,q=j.nodeType?[j]:j;p=n.match.PSEUDO.exec(g);){m+=p[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;p=0;for(var t=q.length;p<t;p++)l(g,q[p],o);return l.filter(m,o)};c.find=l;c.expr=l.selectors;c.expr[":"]=c.expr.filters;c.unique=l.uniqueSort;c.text=l.getText;c.isXMLDoc=l.isXML;c.contains=l.contains})();var Wa=/Until$/,Xa=/^(?:parents|prevUntil|prevAll)/,Ya=/,/,Ja=/^.[^:#\[\.,]*$/,Za=Array.prototype.slice,$a=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("",
"find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var k=0;k<d;k++)if(b[k]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(ka(this,a,false),"not",a)},filter:function(a){return this.pushStack(ka(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,
b){var d=[],e,f,h=this[0];if(c.isArray(a)){var k={},l,n=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:n})}h=h.parentNode;n++}}return d}k=$a.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(k?k.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||
!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context):c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});
c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",
d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Wa.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||Ya.test(e))&&Xa.test(a))f=f.reverse();return this.pushStack(f,a,Za.call(arguments).join(","))}});
c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===A||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var xa=/ jQuery\d+="(?:\d+|null)"/g,
$=/^\s+/,ya=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,za=/<([\w:]+)/,ab=/<tbody/i,bb=/<|&#?\w+;/,Aa=/<(?:script|object|embed|option|style)/i,Ba=/checked\s*(?:[^=]|=\s*.checked.)/i,cb=/\=([^="'>\s]+\/)>/g,O={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],
area:[1,"<map>","</map>"],_default:[0,"",""]};O.optgroup=O.option;O.tbody=O.tfoot=O.colgroup=O.caption=O.thead;O.th=O.td;if(!c.support.htmlSerialize)O._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==A)return this.empty().append((this[0]&&this[0].ownerDocument||u).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,
d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},
unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=
c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));
c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(xa,"").replace(cb,'="$1">').replace($,
"")],e)[0]}else return this.cloneNode(true)});if(a===true){la(this,b);la(this.find("*"),b.find("*"))}return b},html:function(a){if(a===A)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(xa,""):null;else if(typeof a==="string"&&!Aa.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!O[(za.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ya,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?
this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,
true)},domManip:function(a,b,d){var e,f,h=a[0],k=[],l;if(!c.support.checkClone&&arguments.length===3&&typeof h==="string"&&Ba.test(h))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(h))return this.each(function(s){var v=c(this);a[0]=h.call(this,s,b?v.html():A);v.domManip(a,b,d)});if(this[0]){e=h&&h.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);l=e.fragment;if(f=l.childNodes.length===1?l=l.firstChild:
l.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var n=this.length;f<n;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")):this[f]:this[f],f>0||e.cacheable||this.length>1?l.cloneNode(true):l)}k.length&&c.each(k,Ka)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:u;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===u&&!Aa.test(a[0])&&(c.support.checkClone||
!Ba.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=
d.length;f<h;f++){var k=(f>0?this.clone(true):this).get();c(d[f])[b](k);e=e.concat(k)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||u;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||u;for(var f=[],h=0,k;(k=a[h])!=null;h++){if(typeof k==="number")k+="";if(k){if(typeof k==="string"&&!bb.test(k))k=b.createTextNode(k);else if(typeof k==="string"){k=k.replace(ya,"<$1></$2>");var l=(za.exec(k)||["",""])[1].toLowerCase(),n=O[l]||O._default,
s=n[0],v=b.createElement("div");for(v.innerHTML=n[1]+k+n[2];s--;)v=v.lastChild;if(!c.support.tbody){s=ab.test(k);l=l==="table"&&!s?v.firstChild&&v.firstChild.childNodes:n[1]==="<table>"&&!s?v.childNodes:[];for(n=l.length-1;n>=0;--n)c.nodeName(l[n],"tbody")&&!l[n].childNodes.length&&l[n].parentNode.removeChild(l[n])}!c.support.leadingWhitespace&&$.test(k)&&v.insertBefore(b.createTextNode($.exec(k)[0]),v.firstChild);k=v.childNodes}if(k.nodeType)f.push(k);else f=c.merge(f,k)}}if(d)for(h=0;f[h];h++)if(e&&
c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script"))));d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,k=0,l;(l=a[k])!=null;k++)if(!(l.nodeName&&c.noData[l.nodeName.toLowerCase()]))if(d=l[c.expando]){if((b=e[d])&&b.events)for(var n in b.events)f[n]?
c.event.remove(l,n):c.removeEvent(l,n,b.handle);if(h)delete l[c.expando];else l.removeAttribute&&l.removeAttribute(c.expando);delete e[d]}}});var Ca=/alpha\([^)]*\)/i,db=/opacity=([^)]*)/,eb=/-([a-z])/ig,fb=/([A-Z])/g,Da=/^-?\d+(?:px)?$/i,gb=/^-?\d/,hb={position:"absolute",visibility:"hidden",display:"block"},La=["Left","Right"],Ma=["Top","Bottom"],W,ib=u.defaultView&&u.defaultView.getComputedStyle,jb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===A)return this;
return c.access(this,a,b,true,function(d,e,f){return f!==A?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true,zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),k=a.style,l=c.cssHooks[h];b=c.cssProps[h]||
h;if(d!==A){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!l||!("set"in l)||(d=l.set(a,d))!==A)try{k[b]=d}catch(n){}}}else{if(l&&"get"in l&&(f=l.get(a,false,e))!==A)return f;return k[b]}}},css:function(a,b,d){var e,f=c.camelCase(b),h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==A)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=
e[f]},camelCase:function(a){return a.replace(eb,jb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=ma(d,b,f);else c.swap(d,hb,function(){h=ma(d,b,f)});return h+"px"}},set:function(d,e){if(Da.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return db.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":
b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f=d.filter||"";d.filter=Ca.test(f)?f.replace(Ca,e):d.filter+" "+e}};if(ib)W=function(a,b,d){var e;d=d.replace(fb,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return A;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};else if(u.documentElement.currentStyle)W=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],
h=a.style;if(!Da.test(f)&&gb.test(f)){d=h.left;e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f};if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var kb=c.now(),lb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
mb=/^(?:select|textarea)/i,nb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ob=/^(?:GET|HEAD|DELETE)$/,Na=/\[\]$/,T=/\=\?(&|$)/,ia=/\?/,pb=/([?&])_=[^&]*/,qb=/^(\w+:)?\/\/([^\/?#]+)/,rb=/%20/g,sb=/#.*$/,Ea=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ea)return Ea.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=
b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(k,l){if(l==="success"||l==="notmodified")h.html(f?c("<div>").append(k.responseText.replace(lb,"")).find(f):k.responseText);d&&h.each(d,[k.responseText,l,k])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&
!this.disabled&&(this.checked||mb.test(this.nodeName)||nb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})},
getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html",
script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),k=ob.test(h);b.url=b.url.replace(sb,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ia.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data||
!T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+kb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var l=E[d];E[d]=function(m){f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);if(c.isFunction(l))l(m);else{E[d]=A;try{delete E[d]}catch(p){}}v&&v.removeChild(B)}}if(b.dataType==="script"&&b.cache===null)b.cache=
false;if(b.cache===false&&h==="GET"){var n=c.now(),s=b.url.replace(pb,"$1_="+n);b.url=s+(s===b.url?(ia.test(b.url)?"&":"?")+"_="+n:"")}if(b.data&&h==="GET")b.url+=(ia.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");n=(n=qb.exec(b.url))&&(n[1]&&n[1]!==location.protocol||n[2]!==location.host);if(b.dataType==="script"&&h==="GET"&&n){var v=u.getElementsByTagName("head")[0]||u.documentElement,B=u.createElement("script");if(b.scriptCharset)B.charset=b.scriptCharset;B.src=
b.url;if(!d){var D=false;B.onload=B.onreadystatechange=function(){if(!D&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){D=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);B.onload=B.onreadystatechange=null;v&&B.parentNode&&v.removeChild(B)}}}v.insertBefore(B,v.firstChild);return A}var H=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!k||a&&a.contentType)w.setRequestHeader("Content-Type",
b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}n||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(G){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&&
c.triggerGlobal(b,"ajaxSend",[w,b]);var M=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){H||c.handleComplete(b,w,e,f);H=true;if(w)w.onreadystatechange=c.noop}else if(!H&&w&&(w.readyState===4||m==="timeout")){H=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d||
c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&g.call&&g.call(w);M("abort")}}catch(j){}b.async&&b.timeout>0&&setTimeout(function(){w&&!H&&M("timeout")},b.timeout);try{w.send(k||b.data==null?null:b.data)}catch(o){c.handleError(b,w,null,o);c.handleComplete(b,w,e,f)}b.async||M();return w}},param:function(a,b){var d=[],e=function(h,k){k=c.isFunction(k)?k():k;d[d.length]=encodeURIComponent(h)+
"="+encodeURIComponent(k)};if(b===A)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)ca(f,a[f],b,e);return d.join("&").replace(rb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess",[b,a])},handleComplete:function(a,
b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),e=a.getResponseHeader("Etag");
if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}});if(E.ActiveXObject)c.ajaxSettings.xhr=
function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var da={},tb=/^(?:toggle|show|hide)$/,ub=/^([+\-]=)?([\d+.\-]+)(.*)$/,aa,na=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show",3),a,b,d);else{a=
0;for(b=this.length;a<b;a++){if(!c.data(this[a],"olddisplay")&&this[a].style.display==="none")this[a].style.display="";this[a].style.display===""&&c.css(this[a],"display")==="none"&&c.data(this[a],"olddisplay",oa(this[a].nodeName))}for(a=0;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay",d)}for(a=
0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b,d,e);if(c.isEmptyObject(a))return this.each(f.complete);
return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),k,l=this.nodeType===1,n=l&&c(this).is(":hidden"),s=this;for(k in a){var v=c.camelCase(k);if(k!==v){a[v]=a[k];delete a[k];k=v}if(a[k]==="hide"&&n||a[k]==="show"&&!n)return h.complete.call(this);if(l&&(k==="height"||k==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(oa(this.nodeName)===
"inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[k])){(h.specialEasing=h.specialEasing||{})[k]=a[k][1];a[k]=a[k][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(B,D){var H=new c.fx(s,h,B);if(tb.test(D))H[D==="toggle"?n?"show":"hide":D](a);else{var w=ub.exec(D),G=H.cur(true)||0;if(w){var M=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(s,B,(M||1)+g);
G=(M||1)/H.cur(true)*G;c.style(s,B,G+g)}if(w[1])M=(w[1]==="-="?-1:1)*M+G;H.custom(G,M,g)}else H.custom(G,D,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b,
d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a*
Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(h){return f.step(h)}
this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;var f=this;a=c.fx;e.elem=this.elem;if(e()&&c.timers.push(e)&&!aa)aa=setInterval(a.tick,a.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;
this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(l,n){f.style["overflow"+n]=h.overflow[l]})}this.options.hide&&c(this.elem).hide();if(this.options.hide||
this.options.show)for(var k in this.options.curAnim)c.style(this.elem,k,this.options.orig[k]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=
c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(aa);aa=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===
b.elem}).length};var vb=/^t(?:able|d|h)$/i,Fa=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in u.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(k){c.offset.setOffset(this,a,k)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=ea(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&&
h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(s){c.offset.setOffset(this,a,s)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,e=b.ownerDocument,f,h=e.documentElement,k=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;
for(var l=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==k&&b!==h;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;f=e?e.getComputedStyle(b,null):b.currentStyle;l-=b.scrollTop;n-=b.scrollLeft;if(b===d){l+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&vb.test(b.nodeName))){l+=parseFloat(f.borderTopWidth)||0;n+=parseFloat(f.borderLeftWidth)||0}d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&f.overflow!=="visible"){l+=
parseFloat(f.borderTopWidth)||0;n+=parseFloat(f.borderLeftWidth)||0}f=f}if(f.position==="relative"||f.position==="static"){l+=k.offsetTop;n+=k.offsetLeft}if(c.offset.supportsFixedPosition&&f.position==="fixed"){l+=Math.max(h.scrollTop,k.scrollTop);n+=Math.max(h.scrollLeft,k.scrollLeft)}return{top:l,left:n}};c.offset={initialize:function(){var a=u.body,b=u.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",
height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells=
f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a,
"marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),k=c.css(a,"top"),l=c.css(a,"left"),n=e==="absolute"&&c.inArray("auto",[k,l])>-1;e={};var s={};if(n)s=f.position();k=n?s.top:parseInt(k,10)||0;l=n?s.left:parseInt(l,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+k;if(b.left!=null)e.left=b.left-h.left+l;"using"in b?b.using.call(a,
e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Fa.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||u.body;a&&!Fa.test(a.nodeName)&&
c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==A)return this.each(function(){if(h=ea(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=ea(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();
c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(h){var k=c(this);k[d](e.call(this,h,k[d]()))});return c.isWindow(f)?f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b]:f.nodeType===9?Math.max(f.documentElement["client"+
b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]):e===A?parseFloat(c.css(f,d)):this.css(d,typeof e==="string"?e:e+"px")}})})(window);

//]]>
</script>
<script id="jqueryArea" type="text/javascript">
//<![CDATA[
/*
jQuery.encoding.digests.sha1.js

SHA-1 digest and associated utility functions

Copyright (c) UnaMesa Association 2009

Dual licensed under the MIT and GPL licenses:
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html
*/

(function($) {

if(!$.encoding)
	$.encoding = {};
	$.extend($.encoding,{
		strToBe32s: function(str) {
			// Convert a string to an array of big-endian 32-bit words
			var be=[];
			var len=Math.floor(str.length/4);
			var i, j;
			for(i=0, j=0; i<len; i++, j+=4) {
				be[i]=((str.charCodeAt(j)&0xff) << 24)|((str.charCodeAt(j+1)&0xff) << 16)|((str.charCodeAt(j+2)&0xff) << 8)|(str.charCodeAt(j+3)&0xff);
			}
			while(j<str.length) {
				be[j>>2] |= (str.charCodeAt(j)&0xff)<<(24-(j*8)%32);
				j++;
			}
			return be;
		},
		be32sToStr: function(be) {
			// Convert an array of big-endian 32-bit words to a string
			var str='';
			for(var i=0;i<be.length*32;i+=8) {
				str += String.fromCharCode((be[i>>5]>>>(24-i%32)) & 0xff);
			}
			return str;
		},
		be32sToHex: function(be) {
			// Convert an array of big-endian 32-bit words to a hex string
			var hex='0123456789ABCDEF';
			var str='';
			for(var i=0;i<be.length*4;i++) {
				str += hex.charAt((be[i>>2]>>((3-i%4)*8+4))&0xF) + hex.charAt((be[i>>2]>>((3-i%4)*8))&0xF);
			}
			return str;
		}
	});
})(jQuery);


(function($) {

if(!$.encoding.digests)
	$.encoding.digests = {};
	$.extend($.encoding.digests,{
		hexSha1Str: function(str) {
			// Return, in hex, the SHA-1 hash of a string
			return $.encoding.be32sToHex($.encoding.digests.sha1Str(str));
		},
		sha1Str: function(str) {
			// Return the SHA-1 hash of a string
			return sha1($.encoding.strToBe32s(str),str.length);
		},
		sha1: function(x,blen) {
			// Calculate the SHA-1 hash of an array of blen bytes of big-endian 32-bit words
			return sha1($.encoding.strToBe32s(str),str.length);
		}
	});

	// Private functions.
	function sha1(x,blen) {
		// Calculate the SHA-1 hash of an array of blen bytes of big-endian 32-bit words
		function add32(a,b) {
			// Add 32-bit integers, wrapping at 32 bits
			// Uses 16-bit operations internally to work around bugs in some JavaScript interpreters.
			var lsw=(a&0xFFFF)+(b&0xFFFF);
			var msw=(a>>16)+(b>>16)+(lsw>>16);
			return (msw<<16)|(lsw&0xFFFF);
		}
		function AA(a,b,c,d,e) {
			// Cryptographic round helper function. Add five 32-bit integers, wrapping at 32 bits, second parameter is rotated left 5 bits before the addition
			// Uses 16-bit operations internally to work around bugs in some JavaScript interpreters.
			b=(b>>>27)|(b<<5);
			var lsw=(a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF)+(e&0xFFFF);
			var msw=(a>>16)+(b>>16)+(c>>16)+(d>>16)+(e>>16)+(lsw>>16);
			return (msw<<16)|(lsw&0xFFFF);
		}
		function RR(w,j) {
			// Cryptographic round helper function.
			var n=w[j-3]^w[j-8]^w[j-14]^w[j-16];
			return (n>>>31)|(n<<1);
		}

		var len=blen*8;
		x[len>>5] |= 0x80 << (24-len%32);
		x[((len+64>>9)<<4)+15]=len;
		var w=new Array(80);

		var k1=0x5A827999;
		var k2=0x6ED9EBA1;
		var k3=0x8F1BBCDC;
		var k4=0xCA62C1D6;

		var h0=0x67452301;
		var h1=0xEFCDAB89;
		var h2=0x98BADCFE;
		var h3=0x10325476;
		var h4=0xC3D2E1F0;

		for(var i=0;i<x.length;i+=16) {
			var j=0;
			var t;
			var a=h0;
			var b=h1;
			var c=h2;
			var d=h3;
			var e=h4;
			while(j<16) {
				w[j]=x[i+j];
				t=AA(e,a,d^(b&(c^d)),w[j],k1);
				e=d; d=c; c=(b>>>2)|(b<<30); b=a; a=t; j++;
			}
			while(j<20) {
				w[j]=RR(w,j);
				t=AA(e,a,d^(b&(c^d)),w[j],k1);
				e=d; d=c; c=(b>>>2)|(b<<30); b=a; a=t; j++;
			}
			while(j<40) {
				w[j]=RR(w,j);
				t=AA(e,a,b^c^d,w[j],k2);
				e=d; d=c; c=(b>>>2)|(b<<30); b=a; a=t; j++;
			}
			while(j<60) {
				w[j]=RR(w,j);
				t=AA(e,a,(b&c)|(d&(b|c)),w[j],k3);
				e=d; d=c; c=(b>>>2)|(b<<30); b=a; a=t; j++;
			}
			while(j<80) {
				w[j]=RR(w,j);
				t=AA(e,a,b^c^d,w[j],k4);
				e=d; d=c; c=(b>>>2)|(b<<30); b=a; a=t; j++;
			}
			h0=add32(h0,a);
			h1=add32(h1,b);
			h2=add32(h2,c);
			h3=add32(h3,d);
			h4=add32(h4,e);
		}
		return [h0,h1,h2,h3,h4];
	}
})(jQuery);
/*
jQuery.twStylesheet.js

jQuery plugin to dynamically insert CSS rules into a document

Usage:
  jQuery.twStylesheet applies style definitions
  jQuery.twStylesheet.remove neutralizes style definitions

Copyright (c) UnaMesa Association 2009

Triple licensed under the BSD, MIT and GPL licenses:
  http://www.opensource.org/licenses/bsd-license.php
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html
*/

(function($) {

var defaultId = "customStyleSheet"; // XXX: rename to dynamicStyleSheet?

// Add or replace a style sheet
// css argument is a string of CSS rule sets
// options.id is an optional name identifying the style sheet
// options.doc is an optional document reference
// N.B.: Uses DOM methods instead of jQuery to ensure cross-browser comaptibility.
$.twStylesheet = function(css, options) {
	options = options || {};
	var id = options.id || defaultId;
	var doc = options.doc || document;
	var el = doc.getElementById(id);
	if(doc.createStyleSheet) { // IE-specific handling
		if(el) {
			el.cssText = css;
		} else {
			doc.getElementsByTagName("head")[0].insertAdjacentHTML("beforeEnd",
				'&nbsp;<style id="' + id + '" type="text/css">' + css + '</style>'); // fails without &nbsp;
		}
	} else { // modern browsers
		if(el) {
			el.replaceChild(doc.createTextNode(css), el.firstChild);
		} else {
			el = doc.createElement("style");
			el.type = "text/css";
			el.id = id;
			el.appendChild(doc.createTextNode(css));
			doc.getElementsByTagName("head")[0].appendChild(el);
		}
	}
};

// Remove existing style sheet
// options.id is an optional name identifying the style sheet
// options.doc is an optional document reference
$.twStylesheet.remove = function(options) {
	options = options || {};
	var id = options.id || defaultId;
	var doc = options.doc || document;
	var el = doc.getElementById(id);
	if(el) {
		el.parentNode.removeChild(el);
	}
};

})(jQuery);
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
if(useJavaSaver)
	document.write("<applet style='position:absolute;left:-1px' name='TiddlySaver' code='TiddlySaver.class' archive='TiddlySaver.jar' width='1' height='1'></applet>");
//]]>
</script>
<!--POST-SCRIPT-START-->

<!--POST-SCRIPT-END-->
</body>
</html>
